YXH
YXH

Reputation: 401

How to add all the numbers together in some lists, in python

x=[1,2,5] y=[2,3,9] how can I get the result 22?

my code has type error.

Upvotes: 0

Views: 1035

Answers (3)

Avinash Y
Avinash Y

Reputation: 66

>>> list1 = [1,2,5]

>>> list2 = [2,3,9]

>>> zip_list = [(x + y) for x, y in zip(list1, list2)]

>> zip_list

[3, 5, 14]

>>> sum(zip_list)

22

Upvotes: 1

raton
raton

Reputation: 428

    sm=0
    for v in x+y:
         sm=sm+v

Upvotes: 0

mgilson
mgilson

Reputation: 309909

I think you want the built-in sum function.

>>> x = [1,2,5]
>>> y = [2,3,9]
>>> sum(x+y)
22

This is the same thing as:

sum(x) + sum(y)

or if you love itertools:

sum(itertools.chain(x,y))

with the latter 2 being more efficient.


sum takes an iterable and sums all of it's elements. when dealing with lists + concatenates, so:

x+y

gives you the list:

[1,2,5,2,3,9]

which is iterable and therefore a perfect candidate for sum.


If you have a whole bunch of lists you could make this even more interesting:

>>> lists = [x,y]
>>> sum(sum(lst) for lst in lists)
22

This last form is nice because it scales trivially up to an arbitrary number of lists -- just keep appending them to the lists list until you're ready to sum, pop that 1-liner in there and then you're done.

Of course, I suppose we could do the same thing with itertools as well:

sum(itertools.chain.from_iterable(lists))

As you can see, you have quite a few options to play with (and learn from! :).

Upvotes: 6

Related Questions