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'
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'
You don't need the assignment,
list.append(x)
will always appendx
toa
and therefore there's no need te redefinea
.is all you need. This works because
list
s are mutable.Also see the docs on data structures.
No need to re-assign.
The
list.append
function does not return any value(butNone
), it just add 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 ofappend
) toa
, then in the second round it will try to calla.append
, asa is None
it will raise the Exception you are seeingYou just need to change it to:
Edit: As Juan said in comments it does return something,
None