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

In Python 2.7 the following works without problems:

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

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

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

Please, can anyone explain the reason for this error in Python 3.3.4 and, where possible, to provide a solution?

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

Thanks a lot in advance, MRJ.

+6
source share
2 answers

In python2, range returns a list.

In Python3, range returns the object range . Object range does not add method. To fix, convert a range object to the list:

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

The object range - it is an iterator. He deliberately avoids the formation of a list of all values, because it requires more memory, and often people use the range just to keep track of the counter - a use which does not require the simultaneous storage of the full list in the memory.

Of documents :

range type advantage over conventional list or tuple is that the range of the object will always be the same (small) amount of memory no regardless of band size, it represents (as it stores only the values โ€‹โ€‹of the start, stop, and step calculation of individual elements and subbands as required).

+19
source

Note unutbu answer to find out why you can not add to the range() .

However maintain range() -s iterative approach, using itertools.chain() instead of making it in the list and attached thereto. It's 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] ), [ >>> from itertools import chain >>> c = chain(range(10,100,10), [200]) >>> list(c) >>> [10, 20, 30, 40, 50, 60, 70, 80, 90, 200] 

Note: This list(c) also forced object chain and was used only for the view. Instead, use the object chain in the loop for .

+7
source

All Articles