-2

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?

kylieCatt
  • 10,672
  • 5
  • 43
  • 51
bob
  • 21
  • 1

5 Answers5

1

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)
Marcin
  • 215,873
  • 14
  • 235
  • 294
1

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.

Here is more information about modulus.

Community
  • 1
  • 1
David.Jones
  • 1,413
  • 8
  • 16
0
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
Anthony
  • 3,492
  • 1
  • 14
  • 9
0

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.

Nick Humrich
  • 14,905
  • 8
  • 62
  • 85
0
a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
sum(filter(lambda x:x%2==0,a+b+c))
MartinP
  • 527
  • 5
  • 17