how to iterate over 2 lists at same time? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
- 2

how to iterate over 2 lists at same time?

here is a example what i want x = [1,2,3] y = [1,4,9] for i in x: for j in y these two for loops should run combined but how?

1st Aug 2021, 12:47 PM
Bhavik Mahalle
Bhavik Mahalle - avatar
5 ответов
+ 1
for i, j in zip(x, y): # your code
1st Aug 2021, 3:41 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 6
lol even easier. for i in range(len(x)): # your code What is the issue? Bhavik Mahalle if the iterables have the same length, you can just get length of one of them. Then do whatever to both iterables in the loop cause they use the same indexes
1st Aug 2021, 12:54 PM
Slick
Slick - avatar
+ 4
Bhavik Mahalle , the best way is to use zip, but it can also be done with for loop: (enumerate() is used to get additionally an index, which is used in the loop body to access the values) x = [1,2,3] y = [1,4,9] for ind, _ in enumerate(x): print(f"{x[ind]} - {y[ind]}") # result: 1 - 1 2 - 4 3 - 9
6th Aug 2021, 7:03 PM
Lothar
Lothar - avatar
+ 1
for i in x: for j in y: # your code
1st Aug 2021, 12:50 PM
Slick
Slick - avatar
0
Slick wow that's genius
1st Aug 2021, 12:56 PM
Bhavik Mahalle
Bhavik Mahalle - avatar