Python list initialization using multiple range statements

Try this for Python 2.x:

 range(1,6) + range(15,20)

Or if you're using Python3.x, try this:

list(range(1,6)) + list(range(15,20))

For dealing with elements in-between, for Python 2.x:

range(101,6284) + [8001,8003,8010] + range(10000,12322)

And finally for dealing with elements in-between, for Python 3.x:

list(range(101,6284)) + [8001,8003,8010] + list(range(10000,12322))

The key aspects to remember here is that in Python 2.x range returns a list and in Python 3.x it returns an iterable (so it needs to be explicitly converted to a list). And that for appending together lists, you can use the + operator.


You can use itertools.chain to flatten the output of your range() calls.

import itertools
new_list = list(itertools.chain(xrange(1,6), xrange(15,20)))

Using xrange (or simply range() for python3) to get an iterable and chaining them together means only one list object gets created (no intermediate lists required).

If you need to insert intermediate values, just include a list/tuple in the chain:

new_list = list(itertools.chain((-3,-1), 
                                xrange(1,6), 
                                tuple(7),  # make single element iterable
                                xrange(15,20)))