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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM