Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multi-lists iteration

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)
like image 912
user278064 Avatar asked May 02 '12 17:05

user278064


People also ask

Can you loop through two lists at once Python?

Example 2: Using itertools (Python 2+)Using the zip_longest() method of itertools module, you can iterate through two parallel lists at the same time. The method lets the loop run until the longest list stops.

Can list be iterated in Python?

We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list.

How do you cycle through a list in Python?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.

Can I iterate through a list?

Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element.


1 Answers

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.

like image 79
NPE Avatar answered Nov 10 '22 08:11

NPE