Search code examples
pythonpython-2.7python-3.xappendrange

Python 3, range().append() returns error: 'range' object has no attribute 'append'


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'

What is the reason for this error in Python 3.3.4, and what is the solution?

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


Solution

  • 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 a lazy sequence. 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).