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