Multiple indexes iteration in Python's for loop

Viewed 586

I have 4 lists, I want to iterate through the fours at once. here's an example of what I want to achieve

I'm on Python 3.8

list1 = [1,2,3]
list2 = [10,20,30]
list3 = [44,55,66]
list4 = ['a', 'b', 'c']

for i,j,k,,l in (list1, list2, list3, list4):
    print(i,j,k,l)

Output:

1, 10, 44, a
2, 20, 55, b
3, 30, 66, c

How can I achieve that ?

Thanks,

4 Answers

You are looking for this:

list1 = [1,2,3]
list2 = [10,20,30]
list3 = [44,55,66]
list4 = ['a', 'b', 'c']

for i in range(len(list1)):
    print(list1[i], list2[i], list3[i], list4[i])

You loop through using a loop counter i, which is a list index. Then, you index each of the lists at that index to retrieve the values.

You may also want to read more about the range() function in Python, which in this case returns a sequence of numbers starting at 0 and finishing at len(list1) - 1, allowing you to loop through using i as an index.

Use zip to combine each list together and iterate through them

list1 = [1,2,3]
list2 = [10,20,30]
list3 = [44,55,66]
list4 = ['a', 'b', 'c']

for values in zip(list1, list2, list3, list4):
    print(*values)

Output:

1 10 44 a
2 20 55 b
3 30 66 c

As values will contain a tuple, the * will unpack it for you.

Not sure if this is what you are looking for but we can zip all 4 list and read them:

for i in zip(list1,list2,list3,list4):
    print(i)

Come in late, all prev. posts have done great answering the question. Here is to sum up and answer - what if I want to different ordering on the 4 items:

>>> for value_tpl in zip(list1, list2, list3, list4):
    n1, n2, n3, label = value_tpl
    print(label, n3, n2, n1)

    
A 44 10 1
B 55 20 2
C 66 30 3
Related