18

In Python 2.7 the following works without a problem:

myrange = range(10,100,10)
myrange.append(200)
print(my range)

Output: [10,20,30,40,50,60,70,80,90,200]

Conversely, in Python 3.3.4 the same code snippet returns the error: 'range' object has no attribute 'append'

Please could someone explain the reason for this error in Python 3.3.4, and where possible, provide a solution?

The desired output: [10, 20, 30, 40, 50, 60, 70, 80, 90, 200].

Many thanks in advance, mrj.

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
MRJ
  • 187
  • 1
  • 1
  • 6

2 Answers2

49

In Python2, range returns a list.

In Python3, range returns a range object. The range object does not have an append method. To fix, convert the range object to a list:

>>> myrange = list(range(10,100,10))
>>> myrange.append(200)
>>> myrange
[10, 20, 30, 40, 50, 60, 70, 80, 90, 200]

The range object is an iterator. It purposefully avoids forming a list of all the values since this requires more memory, and often people use range simply to keep track of a counter -- a usage which does not require holding the full list in memory at once.

From the docs:

The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
12

Check unutbu's answer to know why you can't append to a range().

However, keep range()-s iterating approach by using itertools.chain() instead of forcing it to a list and appending to it then. It is faster and more efficient.

>>> from itertools import chain
>>> c = chain(range(10,100,10), [200])
>>> list(c)
>>> [10, 20, 30, 40, 50, 60, 70, 80, 90, 200]

Note: Here list(c) also forced the chain object and was used only for representation. Use the chain object in a for loop instead.

Community
  • 1
  • 1
SzieberthAdam
  • 3,999
  • 2
  • 23
  • 31
  • Thank you for the alternative approach. Definitely works, though the first answer provided a little more educational material for me :) – MRJ Mar 16 '14 at 14:18
  • 2
    Sure, I just wanted to point that it is recommended to stick to iterators as long as possible. – SzieberthAdam Mar 16 '14 at 18:30