Reputation: 283
Given A
and B
are lists of integers, how would you add the individual elements and create a new list using their sums? What is the issue with this code and how would you do this? The errors are respectively:
ValueError: too many values to unpack
and
NameError: name 'b' is not defined
C = [a+b for (a,b) in (A,B)]
C = [a+b for a in A, b in B]
Upvotes: 0
Views: 256
Reputation: 104102
You can use map, sum, and zip:
>>> A=[1,2,3]
>>> B=[10,20,30]
>>> map(sum, zip(A, B))
[11, 22, 33]
If your lists are of different lengths, you can use izip_longest with a value of 0 for a fillvalue:
>>> from itertools import izip_longest
>>> A=[1,2,3]
>>> B=[10,20,30,40]
>>> map(sum, izip_longest(A, B, fillvalue=0))
[11, 22, 33, 40]
>>> map(sum, izip_longest(A, B, [100], fillvalue=0))
[111, 22, 33, 40]
Upvotes: 0
Reputation: 236150
Try this, assuming that both lists are of equal size:
C = [a+b for (a,b) in zip(A,B)]
The trick here is using the zip()
built-in function for joining both lists pair-wise.
Upvotes: 6