I have 2 lists of the same size.
list1 = [start1,start2,start3, start4]
list2 = [end1, end2, end3, end4]
startn
in list1
corresponds to endn
in list2
.
I want to use both the lists in a single for
loop for further calculations.
Problem being: I want to use a combination of 2 elements from each list in the for
loop. For example:
I want to extract start1
, start3
from list1
and end1
, end3
from list2
and use these 4 values in a for
loop.
For a single list, to extract a combination of 2 elements, I know it's the following code:
import itertools
for a, b in itertools.combinations(mylist, 2):
But how do I extract 2 values from list1
and the same corresponding values from list2
and use in a for
loop?
You can zip
the two lists and then use combination
to pull out the values:
list1 = ['a', 'b', 'c', 'd']
list2 = [1,2,3,4]
from itertools import combinations
for x1, x2 in combinations(zip(list1, list2), 2):
print(x1, x2)
#(('a', 1), ('b', 2))
#(('a', 1), ('c', 3))
#(('a', 1), ('d', 4))
#(('b', 2), ('c', 3))
#(('b', 2), ('d', 4))
#(('c', 3), ('d', 4))