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
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)
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.
range
has a __add__
method implemented, that's why. Can someone confirm?
itertools.chain
, as it avoids creating temporary lists, which might be a memory hog for large ranges.
Commented
Jun 27, 2017 at 20:32
itertools.chain
them into a single iterable.range(1) + range(2)