为什么“ x = x.append (...)”在 for 循环中不起作用?

我试图反复在列表的末尾添加对象,如下所示:

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

但是我得到一个错误,比如: AttributeError: 'NoneType' object has no attribute 'append'。这是因为 list1开始时是一个空列表吗?如何修复此错误?


这个问题特别关于如何修复问题并正确地附加到列表中。在原始代码中,使用循环时会出现报告的错误,因为 .append第一次返回 None。对于返回的 为什么None(底层设计决策) ,请参阅 为什么这些列表操作返回 Nothing,而不是结果列表?

如果你有一个 IndexError从试图分配到一个索引刚刚超过一个列表的末尾-这是不工作的,你需要的 .append方法代替。有关更多信息,请参见 为什么这个迭代列表增长代码给 IndexError: list 赋值索引超出了范围?如何重复向列表中添加元素?

如果要多次附加 一样值,请参见 Python: 将条目附加到列表 N 次

265209 次浏览

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

append returns None, so at the second iteration you are calling method append of NoneType. Just remove the assignment:

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

Like Mikola said, append() returns a void, so every iteration you're setting list1 to a nonetype because append is returning a nonetype. On the next iteration, list1 is null so you're trying to call the append method of a null. Nulls don't have methods, hence your error.

Mikola has the right answer but a little more explanation. It will run the first time, but because append returns None, after the first iteration of the for loop, your assignment will cause list1 to equal None and therefore the error is thrown on the second iteration.

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)).

Note that you also can use insert in order to put number into the required position within list:

initList = [1,2,3,4,5]
initList.insert(2, 10) # insert(pos, val) => initList = [1,2,10,3,4,5]

And also note that in python you can always get a list length using method len()

I personally prefer the + operator than append:

for i in range(0, n):


list1 += [[i]]

But this is creating a new list every time, so might not be the best if performance is critical.

use my_list.append(...) and do not use and other list to append as list are mutable.