Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List append() in for loop [duplicate]

In Python, trying to do the most basic append function to a list with a loop: Not sure what i am missing here:

a=[] for i in range(5):         a=a.append(i) a 

returns: 'NoneType' object has no attribute 'append'

like image 408
jim jarnac Avatar asked Jan 03 '17 21:01

jim jarnac


People also ask

Does list append make a copy?

💡 Tips: When you use . append() the original list is modified. The method does not create a copy of the list – it mutates the original list in memory.

How do you append to a list in loop?

You can append a list in for loop, Use the list append() method to append elements to a list while iterating over the given list.

Does list take duplicate values?

A Python list can also contain duplicates, and it can also contain multiple elements of different data types. This way, you can store integers, floating point numbers, positive or negatives, strings, and even boolean values in a list.


2 Answers

The list.append function does not return any value(but None), it just adds the value to the list you are using to call that method.

In the first loop round you will assign None (because the no-return of append) to a, then in the second round it will try to call a.append, as a is None it will raise the Exception you are seeing

You just need to change it to:

a=[] for i in range(5):         a.append(i) print(a) # [0, 1, 2, 3, 4] 

list.append is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).

If you would like to create a new list based in one list without destroying or mutating it you can do something like this:

a=['a', 'b', 'c'] result = a + ['d']  print result # ['a', 'b', 'c', 'd']  print a # ['a', 'b', 'c'] 

As a corollary only, you can mimic the append method by doing the following:

a=['a', 'b', 'c'] a = a + ['d']  print a # ['a', 'b', 'c', 'd'] 
like image 89
Rafael Aguilar Avatar answered Oct 15 '22 10:10

Rafael Aguilar


You don't need the assignment, list.append(x) will always append x to a and therefore there's no need te redefine a.

a = [] for i in range(5):         a.append(i) print(a) 

is all you need. This works because lists are mutable.

Also see the docs on data structures.

like image 45
linusg Avatar answered Oct 15 '22 10:10

linusg