novice
novice

Reputation: 29

Python. How to sum up all even integers in a list?

I'm completely new to the subject and I want to ask how to sum up all even integers in a list (without using functions (I haven't studied them yet))? For example:

myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]

I create for loop

for i in myList:
  if x % 2 ==0:
  # I'm stuck here

How to store these values to calculate the sum?

Upvotes: 3

Views: 31051

Answers (4)

Stefan Pochmann
Stefan Pochmann

Reputation: 28596

Sorry, I just had to golf this. Maybe it'll teach someone the ~ operator.

>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> sum(~i%2*i for i in myList)
60

Found another one with the same length:

>>> sum(i&~i%-2for i in myList)
60

Upvotes: 6

Martin Konecny
Martin Konecny

Reputation: 59591

You can filter out all non-even elements like so

my_list = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
even_list = filter(lambda x: x%2 == 0, my_list)

and then sum the output like so:

sum(even_list)

Upvotes: 1

Deacon
Deacon

Reputation: 3803

You need to store the result in a variable and add the even numbers to the variable, like so:

>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> result = 0  # Initialize your results variable.
>>> for i in myList:  # Loop through each element of the list.
...   if not i % 2:  # Test for even numbers.
...     result += i
... 
>>> print(result)
60
>>> 

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49320

Using a generator expression:

>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> sum(num for num in myList if not num%2)
60

Using filter():

>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> sum(filter(lambda x: not x%2, myList))
60

Using a manual loop:

>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> result = 0
>>> for item in myList:
...     if not item%2:
...             result += item
...
>>> result
60

Upvotes: 8

Related Questions