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

Question:

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.

Asked By: MRJ

||

Answers:

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).

Answered By: unutbu

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.

Answered By: SZIEBERTH Ádám

Here list(c) take many time. we need just:

>>> c = list()

This is more efficient!!!

Answered By: A.Zidan