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