These are my lists. How do I add every number from list1
to every number in list2
?
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
outcomelist = [7,8,9,10,11,8,9,11,12,9,10,11,12,13,10,11,12,13,14,1,12,13,14,15]
These are my lists. How do I add every number from list1
to every number in list2
?
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
outcomelist = [7,8,9,10,11,8,9,11,12,9,10,11,12,13,10,11,12,13,14,1,12,13,14,15]
Use zip build-in function and list comprehension
[x + y for x, y in zip([1,2,3,4,5], [6,7,8,9,10])]
>>> [7, 9, 11, 13, 15]
Or don't do zipping
if you want sum up all to all:
[x + y for x in [1,2,3,4,5] for y in [6,7,8,9,10]]
>>> [7, 8, 9, 10, 11, 8, 9, 10, 11, 12, 9, 10, 11, 12, 13, 10, 11, 12, 13, 14, 11, 12, 13, 14, 15]
If you want to build a new list, you can do:
list3 = [x + y for x, y in zip(list1, list2)]
If you what you want is updating list2, you canalso use enumerate to access the index and update the list:
for idx, tuple in enumerate(zip(list1, list2)):
list2[idx] = tuple[1] + tuple[0]
python3
add=lambda x,y:x+y
list(map(add,list1,list2))#[7, 9, 11, 13, 15]
import operator
list(map(operator.add,list1,list2))#[7, 9, 11, 13, 15]
list comperhension:
[x+y for x,y in zip(list1,list2)]#[7, 9, 11, 13, 15]
[sum([x,y]) for x,y in zip(list1,list2)]#[7, 9, 11, 13, 15]
Use itertools.product
to make all the possible pairs:
>>> import itertools
>>> list1 = [1,2,3,4,5]
>>> list2 = [6,7,8,9,10]
>>> [x + y for (x,y) in itertools.product(list1, list2)]
>>> resultlist
[7, 8, 9, 10, 11, 8, 9, 10, 11, 12, 9, 10, 11, 12, 13, 10, 11, 12, 13, 14, 11, 12, 13, 14, 15]
You can extend this to multiple lists:
>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list3 = [7,8,9]
>>> [x + y + z for (x, y, z) in itertools.product(list1, list2, list3)]
Or even variable number of lists:
>>> [sum(items) for items in itertools.products(*list_of_lists)]