Home > Software engineering >  Iterate over multiple lists simultaneously in python
Iterate over multiple lists simultaneously in python

Time:06-12

I have a function that returns an element (elem) that are 3 lists (a,b,c) and I can do the following:

for a,b,c in elem:
    do whatever...

Is there any way I can do the loop simultaneously with 2 of those elements? kind of something like this:

for a,b,c,d,e,f in elem1 and elem2:
    do whatever...

Well, assuming elem1 and elem2 have the same size.

CodePudding user response:

The zip function gives you the elements in pairs.

for (a, b, c), (d, e, f) in zip(elem1, elem2):
    do something...

You could also do it with indexes

for i in range(len(elem1)):
    a, b, c = elem1[i]
    d, e, f = elem2[i]
    do something...

CodePudding user response:

You may iterate objects elem1 and elem2 together using zip function like this:

for (a,b,c),(d,e,f) in zip(elem1, elem2):
    do_whatever(a,b,c,d,e,f)
  • Related