0

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
2
  • No, you'd have to e.g. itertools.chain them into a single iterable.
    – jonrsharpe
    Commented Jun 27, 2017 at 19:47
  • range(1) + range(2)
    – cs95
    Commented Jun 27, 2017 at 19:58

2 Answers 2

4

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)
-1

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.

5
  • 1
    Not in Python 3.x, it won't.
    – jonrsharpe
    Commented Jun 27, 2017 at 19:55
  • "possibly because range is generated on the fly" actually, I don't think range has a __add__ method implemented, that's why. Can someone confirm?
    – cs95
    Commented Jun 27, 2017 at 19:59
  • 1
    @Coldspeed dir(range(1)) confirms your suspicion. Commented Jun 27, 2017 at 20:29
  • 1
    And anyway, even in Python 2.x it is better to use itertools.chain, as it avoids creating temporary lists, which might be a memory hog for large ranges. Commented Jun 27, 2017 at 20:32
  • @Błotosmętek And so it does. Thanks yo.
    – cs95
    Commented Jun 27, 2017 at 20:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.