7

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)

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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)

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.