For example, the lists are [1,2,3]
,[4,5,6]
, and [7,8,9]
. I want to add only the even numbers up in all the lists, so that would be 2+4+6+8=20. How would I go about doing this?
-
How would you go about adding up *all* the numbers in the lists? – Ry- Nov 27 '14 at 22:45
-
1have you made an attempt? – Padraic Cunningham Nov 27 '14 at 22:49
5 Answers
You can just do it like this for example:
l = [[1,2,3], [4,5,6], [7,8,9]]
sum(val for v in l for val in v if val % 2 ==0)

- 215,873
- 14
- 235
- 294
-
-
with `itertools.ifilterfalse` and `itertools.chain`: `>>> sum(ifilterfalse(lambda x: x%2, chain(*[[1,2,3], [4,5,6], [7,8,9]]))) 20 ` – Mazdak Nov 27 '14 at 22:56
Simply loop through each list, and sum up the even values.
theSum = 0
lists = [[1,2,3],[4,5,6],[7,8,9]]
for list in lists:
for item in list:
if item % 2 == 0:
theSum += item
The (%) sign used in this context is known as modulus, it will return the number of remainders when a number is divided by another. So far example here, any number that can be divided by 2 without any remainders is an even number e.g. 8 % 2 returns 0.
if item % 2 == 0:
theSum += item
As you can see by the if statement, we go through all the items and test if they can be divided by 2 without leaving remainders. If they can be, we add them together.

- 1
- 1

- 1,413
- 8
- 16
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
sum = 0
for x in a+b+c:
if x%2 == 0:
sum += x

- 3,492
- 1
- 14
- 9
-
-
Ah, right. Reserved keyword. Thanks! I'll leave the original, but you're right! – Anthony Nov 27 '14 at 22:53
There are many solutions, but here is a good start for you.
You can merge all the lists together into one list:
lst =[1,2,3] + [4,5,6] + [7,8,9]
Then you can make a list of just the evens:
new_list = [n for n in lst if is_even(n)]
Note: you must write is_even
def is_even(n):
# return True if even
# otherwise return False
Then you can iterate through the list and add up all the numbers in the list.

- 14,905
- 8
- 62
- 85