Frank Vel
Frank Vel

Reputation: 1208

Multiple iterators in a single for statement

Is it possible to loop over multiple iterators in a single for-statement?

>>> for i in range(1), range(2):
...  print(i)
...
0
0
1

Upvotes: 0

Views: 1385

Answers (2)

physicist
physicist

Reputation: 904

This is not possible, however you can try alternatives like merging the two ranges to a single list.

for i in (range(1)+ range(2)):
  print(i)

This should work. range(1) and range(2) are expanded to lists and you can always concatenate them using overloaded '+' operator.

PS:wont work in python3, possibly because range is generated on the fly.

Upvotes: -1

user2357112
user2357112

Reputation: 280465

There's nothing built into the for syntax for that; a for loop always loops over one iterable. You can make one iterable backed by a bunch of others, though:

import itertools
for i in itertools.chain(range(1), range(2)):
    print(i)

Upvotes: 4

Related Questions