Reputation: 401
x=[1,2,5] y=[2,3,9] how can I get the result 22?
my code has type error.
Upvotes: 0
Views: 1035
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
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