'How can I combine range() functions

For some code I'm writing, I need to iterate from 1-30 skipping 6. What I tried naively is

a = range(1,6)
b = range(7,31)

for i in a+b:
    print i

Is there a way to do it more efficiently?



Solution 1:[1]

Use itertools.chain:

import itertools

a = range(1,6)
b = range(7,31)

for i in itertools.chain(a, b):
    print i

Or tricky flattening generator expressions:

a = range(1,6)
b = range(7,31)
for i in (x for y in (a, b) for x in y):
    print i

Or skipping in a generator expression:

skips = set((6,))
for i in (x for x in range(1, 31) if x not in skips):
    print i

Any of these will work for any iterable(s), not just ranges in Python 3 or listss in Python 2.

Solution 2:[2]

One option would be to use a skip list, and check against that, with something like:

skips = [6, 42]
for i in range(1,31):
   if i in skips:
      continue
   print i

Solution 3:[3]

I use list conversion:

>>> list(range(10,13)) + list(range(1,5))
[10, 11, 12, 1, 2, 3, 4]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Randomness
Solution 3 twinturbotom