Home > Mobile >  How do we implement multivariable in a for loop in python?
How do we implement multivariable in a for loop in python?

Time:10-02

for(i=0,j=0,k=0; i<x,j<y,k<z; i  ,j  ,k--) // Assuming x,y,z are already initialised

Is there a way to do the same in python in the same line as the loop instead of declaring variables and incrementing inside the loop as

i=0
j=0
for k in range (z):
   .
   .
   .
   i  = 1
   j  = 1

CodePudding user response:

Yes, by creating a generator for each variable and using zip to combine them.

zip will iterate until the shortest generator is exhausted. As an alternative, see itertools.zip_longest.

gen_i = range(x)
gen_j = range(y)
gen_k = range(z, -1, -1)  # your example wasn't quite clear, I interpreted it like this

for i, j, k in zip(gen_i, gen_j, gen_k):
    ...
  • Related