How can I add non-sequential numbers to a range?

Use the built-in + operator to append your non-sequential numbers to the range.

for x in range(750, 765) + [769, 770, 774]: print x

There are two ways to do it.

>>> for x in range(5, 7) + [8, 9]: print x
...
5
6
8
9
>>> import itertools
>>> for x in itertools.chain(xrange(5, 7), [8, 9]): print x
...
5
6
8
9

itertools.chain() is by far superior, since it allows you to use arbitrary iterables, rather than just lists and lists. It's also more efficient, not requiring list copying. And it lets you use xrange, which you should when looping.


The other answers on this page will serve you well. Just a quick note that in Python3.0, range is an iterator (like xrange was in Python2.x... xrange is gone in 3.0). If you try to do this in Python 3.0, be sure to create a list from the range iterator before doing the addition:

for x in list(range(750, 765)) + [769, 770, 774]: print(x)

Tags:

Python

Range