List append() in for loop [duplicate]

2020-02-11 17:44发布

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'

3条回答
【Aperson】
2楼-- · 2020-02-11 17:49

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.

查看更多
贪生不怕死
3楼-- · 2020-02-11 17:52

No need to re-assign.

a=[]
for i in range(5):    
    a.append(i)
a
查看更多
别忘想泡老子
4楼-- · 2020-02-11 17:53

The list.append function does not return any value(but None), 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 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)
a # the list with the new items.

Edit: As Juan said in comments it does return something, None

查看更多
登录 后发表回答