Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

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.

like image 798
MRJ Avatar asked Mar 16 '14 13:03

MRJ


People also ask

How do I fix AttributeError int object has no attribute append?

The Python "AttributeError: 'int' object has no attribute 'append'" occurs when we call the append() method on an integer. To solve the error, make sure the value you are calling append on is of type list .

Has no attribute append?

The AttributeError: 'set' object has no attribute 'append' occurs when you call the append() method on a set. To solve this error you can use the set() methods add() or update() to add one or several items to a set, respectively. Otherwise, you can convert the set to a list using the list() method.

What does str object has no attribute append mean?

The Python "AttributeError: 'str' object has no attribute 'append'" occurs when we try to call the append() method on a string (e.g. a list element at specific index). To solve the error, call the append method on the list or use the addition (+) operator if concatenating strings.

How do you append a range to a list?

Use the list. extend() method to append a range to a list in Python, e.g. my_list. extend(range(2)) . The extend method takes an iterable (such as a range) and extends the list by appending all of the items from the iterable.


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

like image 140
unutbu Avatar answered Oct 03 '22 00:10

unutbu