Concatenating two range function results

MAG picture MAG · Dec 31, 2012 · Viewed 46.5k times · Source

Does range function allows concatenation ? Like i want to make a range(30) & concatenate it with range(2000, 5002). So my concatenated range will be 0, 1, 2, ... 29, 2000, 2001, ... 5001

Code like this does not work on my latest python (ver: 3.3.0)

range(30) + range(2000, 5002)

Answer

Lev Levitsky picture Lev Levitsky · Dec 31, 2012

You can use itertools.chain for this:

from itertools import chain
concatenated = chain(range(30), range(2000, 5002))
for i in concatenated:
     ...

It works for arbitrary iterables. Note that there's a difference in behavior of range() between Python 2 and 3 that you should know about: in Python 2 range returns a list, and in Python3 an iterator, which is memory-efficient, but not always desirable.

Lists can be concatenated with +, iterators cannot.