pythonloopsfiltersumlist-comprehension

A more pythonic way to filter out even numbers from a list and calculate the sum?


I have a list of numbers in Python, and I’m trying to get the sum of only the odd numbers. I know I can use a for loop, but is there a more Pythonic way to do this?

Here’s what I have so far, but it seems a bit long

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sum_of_odds = 0
for number in numbers:
    if number % 2 != 0:
        sum_of_odds += number
print(sum_of_odds)

Solution

  • I believe this is a shorter and more "Pythonic" way to do it:

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    sum_of_odds = sum(number for number in numbers if number % 2 != 0)
    print(sum_of_odds)
    

    The use of generator expressions here along with sum() is more efficient (partly because it avoids creating an intermediate list). We then use an inline if-statment (number % 2 != 0) to filter the numbers.