python3学习笔记--list.append()/extend()/+=

list插入一个元素时

a=[1,2,3]
a.append(2)
a+=[2]
a.extend([2])

以上三种方法等价; list结尾处插入list中的元素时:

>>>a=[1,2,3]
>>>a.extend(a)
>>>a
[1,2,3,1,2,3]
>>>a+=a
>>>a
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>>a=[1,2,3]
>>>a.append(a)
>>>a
[1, 2, 3, [...]]
>>>a[-1]==a
True

+=和extend相当于把列表的元素加入到列表的结尾。

list.extend(L): Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

append相当于把list插入到原有list的结尾处,造成对自己的引用,形成了无限循环。

list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x].

原文地址:https://www.cnblogs.com/straight/p/7718139.html