Thursday, December 3, 2026 | London 10°C · Drizzle
DailyGlimpse

AI

Python Trick: Count Conditions with sum() Instead of a Counter Variable

CodersAura 1 min read

Many Python beginners write a counter variable to count how many items passed a condition. But Python has a cleaner shortcut: use sum() with a generator expression.

Each condition returns True or False. In numeric contexts, True behaves like 1 and False behaves like 0. So sum() can count how many conditions were True. This is useful for filters, checks, and quick reports.

Example: count = sum(x > 0 for x in numbers)

This trick makes code more concise and readable. For more Python tips, check out CodersAura.

React