how.wtf

Iterate through two lists in parallel in Python

· Thomas Taylor

Iterating through a two lists in parallel is natively handled in Python using the zip function.

Iterate through two lists using zip

Python’s zip function will aggregate elements from two or more iterables.

1foo = ["x", "y", "z"]
2bar = [1, 2, 3]
3
4for f, b in zip(foo, bar):
5  print(f, b)

Output:

1x 1
2y 2
3z 3

This works with any number of iterables:

1foo = ["x", "y", "z"]
2bar = [1, 2, 3]
3baz = ["!", "@", "#"]
4
5for f, b, z in zip(foo, bar, baz):
6  print(f, b, z)

Output:

1x 1 !
2y 2 @
3z 3 #

If the index is necessary, use enumerate:

1foo = ["x", "y", "z"]
2bar = [1, 2, 3]
3
4for i, (f, b) in enumerate(zip(foo, bar)):
5  print(i, f, b)

Output:

10 x 1
21 y 2
32 z 3

#Python  

Reply to this post by email ↪