2

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,

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Hamouza
  • 356
  • 3
  • 12

4 Answers4

2

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.

costaparas
  • 5,047
  • 11
  • 16
  • 26
  • Thanks for your answer, I was looking for a way more 'elegant' way to do it, I know how to do it with 2 indexes (for i,j in zip(list1, list2), ans was looking out of curiosity if you can do it for more than 2 lists – Hamouza Jan 15 '21 at 14:40
2

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.

Nic Laforge
  • 1,776
  • 1
  • 8
  • 14
2

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)
-2

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
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23