Reputation: 10180
Is there a clever way to iterate over two lists in Python (without using list comprehension)?
I mean, something like this:
# (a, b) is the cartesian product between the two lists' elements
for a, b in list1, list2:
foo(a, b)
instead of:
for a in list1:
for b in list2:
foo(a, b)
Upvotes: 7
Views: 233
Reputation: 1
Use zip it allows you to zip two or more lists and iterate at a time.
list= [1, 2]
list2=[3,4]
combined_list = zip(list, list2)
for a in combined_list:
print(a)
Upvotes: 0
Reputation: 7338
for a,b in zip(list1, list2):
foo(a,b)
zip
combines the elements of lists / arrays together element wise into tuples. e.g.
list1 = [1,2,5]
list2 = [-2,8,0]
for i in zip(list1,list2):
print(i)
>>> (1, -2)
>>> (2, 8)
>>> (5, 0)
Upvotes: 0
Reputation: 500663
itertools.product()
does exactly this:
for a, b in itertools.product(list1, list2):
foo(a, b)
It can handle an arbitrary number of iterables, and in that sense is more general than nested for
loops.
Upvotes: 14