5 Best Ways to Count Even and Odd Numbers in a Python List

πŸ’‘ Problem Formulation: Consider you have a list of integers in Python: [1, 2, 3, 4, 5, 6]. Your task is to write a Python program to count how many even numbers and how many odd numbers are present in this list. The desired output for this list would be a tuple like (3, 3), indicating three even numbers and three odd numbers.

Method 1: Using Loops

The loop method involves iterating over the list and incrementing separate counters for even and odd numbers. It’s straightforward and easily understandable.

Here’s an example:

nums = [1, 2, 3, 4, 5, 6]
even_count, odd_count = 0, 0
for num in nums:
    if num % 2 == 0:
        even_count += 1
    else:
        odd_count += 1
print((even_count, odd_count))

Output: (3, 3)

This Python code snippet introduces two counters, even_count and odd_count, initialized to zero. It uses a ‘for loop’ to traverse the list, nums, and the modulus operator (%) to distinguish even and odd numbers, incrementing the corresponding counter accordingly before printing the results.

Method 2: Using List Comprehension

List comprehension in Python provides a compact and elegant way to filter elements. This method uses two list comprehensions to create separate lists of even and odd numbers, and then gets their lengths.

Here’s an example:

nums = [1, 2, 3, 4, 5, 6]
even_count = len([num for num in nums if num % 2 == 0])
odd_count = len([num for num in nums if num % 2 != 0])
print((even_count, odd_count))

Output: (3, 3)

Using list comprehension, we quickly obtain the sublist of even numbers and another for odd numbers from nums. The function len() then gives us the counts. While this is more concise, it may not be as performance-efficient for very large lists as it creates temporary lists in memory.

Method 3: Using the filter() Function

The filter() function is a built-in function in Python that constructs an iterator from elements of an iterable for which a function returns true. Here, it is used in combination with a lambda function to separate the even and odd numbers.

Here’s an example:

nums = [1, 2, 3, 4, 5, 6]
even_count = len(list(filter(lambda x: (x%2 == 0), nums)))
odd_count = len(list(filter(lambda x: (x%2 != 0), nums)))
print((even_count, odd_count))

Output: (3, 3)

The filter() function is used twice with appropriate lambda functions to isolate the even and odd numbers respectively. The len() function is then used to determine the counts. It’s a clean approach but may not be the most intuitive for beginners.

Method 4: Using collections.Counter

The collections module provides specialized container datatypes, and Counter is one of them, well-suited for tallying a list. This method avoids explicit looping and makes the code compact and readable.

Here’s an example:

from collections import Counter

nums = [1, 2, 3, 4, 5, 6]
parity_counts = Counter('even' if num % 2 == 0 else 'odd' for num in nums)
print((parity_counts['even'], parity_counts['odd']))

Output: (3, 3)

This snippet uses a generator expression to feed into Counter, which creates a dictionary-like object counting occurrences of ‘even’ and ‘odd’ labels applied to each number. We then extract the counts using the label names as keys.

Bonus One-Liner Method 5: Using Python’s sum() Function

Python’s built-in sum() function can be used with a generator expression to add 1 for each even or odd number encountered in the list, resulting in a one-liner solution.

Here’s an example:

nums = [1, 2, 3, 4, 5, 6]
even_count = sum(1 for num in nums if num % 2 == 0)
odd_count = len(nums) - even_count
print((even_count, odd_count))

Output: (3, 3)

This sleek one-liner utilizes the sum() function to count even numbers using a generator expression. It calculates the number of odd items indirectly by subtracting the count of even numbers from the total list length.

Summary/Discussion

  • Method 1: Using Loops. Strengths: Intuitive and easy for beginners to understand. Weaknesses: Can be verbose for simple counting operations.
  • Method 2: Using List Comprehension. Strengths: Concise and leverages Python’s syntactic sugar. Weaknesses: Memory-intensive for large lists due to creation of temporary lists.
  • Method 3: Using the filter() Function. Strengths: Functional programming approach, clean and expressive. Weaknesses: Can be less approachable for those not familiar with lambda functions.
  • Method 4: Using collections.Counter. Strengths: Avoids explicit looping and offers a high-level abstraction. Weaknesses: Requires understanding of the Collections module and its Counter class.
  • Method 5: One-Liner Using sum(). Strengths: Extremely compact and efficient for small to medium-sized lists. Weaknesses: Less readable, and the use of subtraction to find odd count might not be immediately obvious.