Examples of how to iterate over two lists or more in python
Iterate over two lists of same size
A simple solution is to use the function zip
>>> l1 = ['a','b','c']>>> l2 = [1,2,3]>>> for x,y in zip(l1,l2):... print(x,y)...a 1b 2c 3
Iterate over three lists of same size
Another example:
>>> l1 = ['a','b','c']>>> l2 = [1,2,3]>>> l3 = ['hello','hi','bye']>>> for x,y,z in zip(l1,l2,l3):... print(x,y,z)...a 1 hellob 2 hic 3 bye
Iterate over lists of different sizes
An example of solution to iterate over two lists of different sizes
>>> l1 = ['a','b','c','d','e','f']>>> l2 = [1,2,3]>>> min_length = min(len(l1), len(l2))>>> for x,y in zip(l1[:min_length],l2[:min_length]):... print(x,y)...a 1b 2c 3
References
| Links | Site |
|---|---|
| zip | python doc |
| zip lists in python | stackoverflow |
| Combining two lists | stackoverflow |
| Python:get a couple of values from two different list | stackoverflow |
| Is there a better way to iterate over two lists, getting one element from each list for each iteration? | stackoverflow |
