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)
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With