Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append to the end of an empty list?

Tags:

python

I have a list:

list1=[] 

the length of the list is undetermined so I am trying to append objects to the end of list1 like such:

for i in range(0, n):      list1=list1.append([i]) 

But my output keeps giving this error: AttributeError: 'NoneType' object has no attribute 'append'

Is this because list1 starts off as an empty list? How do I fix this error?

like image 949
LostLin Avatar asked Jun 14 '11 04:06

LostLin


People also ask

How do you append to the end of a list in Python?

The append() Python method adds an item to the end of an existing list. The append() method does not create a new list. Instead, original list is changed. append() also lets you add the contents of one list to another list.

How do you append a string to the end of a list?

Adding a string to a list inserts the string as a single element, and the element will be added to the list at the end. The list. append() will append it to the end of the list.

Does append add to the end of a list?

append() method adds the entire item to the end of the list. If the item is a sequence such as a list, dictionary, or tuple, the entire sequence will be added as a single item of the existing list.


2 Answers

append actually changes the list. Also, it takes an item, not a list. Hence, all you need is

for i in range(n):    list1.append(i) 

(By the way, note that you can use range(n), in this case.)

I assume your actual use is more complicated, but you may be able to use a list comprehension, which is more pythonic for this:

list1 = [i for i in range(n)] 

Or, in this case, in Python 2.x range(n) in fact creates the list that you want already, although in Python 3.x, you need list(range(n)).

like image 85
Andrew Jaffe Avatar answered Sep 30 '22 10:09

Andrew Jaffe


You don't need the assignment operator. append returns None.

like image 45
Mikola Avatar answered Sep 30 '22 10:09

Mikola