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?
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.
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.
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.
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))
.
You don't need the assignment operator. append returns None.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With