3

I have the following code:

for inc in range(0, ninc+1)+range(ninc-1,-1,-1):

But it gives me such an error:

for inc in range(0, ninc+1)+range(ninc-1,-1,-1):
TypeError: unsupported operand type(s) for +: 'range' and 'range'

I am using Python 3.3.2. Any suggestions?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
nicomedian
  • 53
  • 1
  • 7

4 Answers4

5

range objects aren't lists, so you can't add them together. You can, however, chain the two iterables:

import itertools

for inc in itertools.chain(range(0, ninc + 1), range(ninc - 1, -1, -1)):
    ...
Blender
  • 289,723
  • 53
  • 439
  • 496
2

Python 3.x's range doesn't return a list, but a range object. So, we have to create a list out of that object like this

rlist = list(range(0, ninc+1))
for inc in rlist + rlist[-2::-1]:
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

Use itertools.chain:

from itertools import chain
myIterator = chain(range(0, ninc + 1), range(ninc - 1, -1, -1))
for x in myIterator:
..

or something similar.

Found from https://stackoverflow.com/a/14099894/3093524

Community
  • 1
  • 1
Joel R
  • 49
  • 3
0

Maybe range.extend (python2 only)

range_1 = range(2)
range_2 = range(3)
range_1.extend(range_2)

print(range_1)
[0, 1, 0, 1, 2]
Cameron White
  • 542
  • 4
  • 10
  • This won't work in Python 3; there is no `range.extend`, there's only `list.extend`, and in Python 3 `range` doesn't return a `list`. – DSM Dec 29 '13 at 16:59