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:
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
>>>
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
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
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)