Python Count Evens
% moduloPractice

Count even numbers in a list

x % 2 == 0 checks divisibility by 2. Combine it with sum() and a generator to count in one elegant line.

Picture this: count the even boxes

Visit each number. If it is even, add 1 to the counter.

each nin the list
→
n % 2 == 0?even?
→
count += 1yes
→
print(count)how many

In easy words: What is this task?

From a list of numbers, count how many are even numbers. Even numbers divide by 2 without any remainder.

Where this is used

Used when filtering IDs, grouping seats (odd/even), selecting alternating hardware ports, or quickly counting items that match a numeric rule.

Theory: modulo and list filters

  • x % 2 == 0 is True for even numbers, False for odd.
  • sum(1 for x in nums if x % 2 == 0) counts matching items without a manual loop variable.
  • This pattern (generator expression + sum) is idiomatic Python for counting.

Real world: inventory sorting

A warehouse app checks which shelf IDs are even-numbered (reserved for heavy items). The same % 2 == 0 filter runs on thousands of shelf numbers instantly.

Green = even, faded = odd

0
even numbers
in the list
1print(sum(1 for x in nums if x % 2 == 0))

Example Program

1nums = [2, 3, 4, 5, 6]
2print(sum(1 for x in nums if x % 2 == 0))