list.pop()和list = list [:-1]之间的区别 [英] Difference between list.pop() and list = list[:-1]

查看:111
本文介绍了list.pop()和list = list [:-1]之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> a = [1,2,3]
>>> a.pop()
3
>>> a
[1, 2]
>>> a = [1,2,3]
>>> a = a[:-1]
>>> a
[1, 2]
>>>

上述从列​​表中删除最后一个元素的方法之间是否有区别?

Is there any difference between the above methods to remove the last element from a list?

推荐答案

是. pop 为O(1)并变异原始列表,而slice为O(n)并创建列表的副本.非正式地, pop 方法是对列表末尾元素的操作,在CPython中定义为对 list_resize(self,Py_SIZE(self)-1); 的调用.这不会遍历整个结构.

Yes. pop is O(1) and mutates the original list, while slice is O(n) and creates a copy of the list. Less formally, the pop method is an operation on the element at the end of the list and is defined in CPython as a call to list_resize(self, Py_SIZE(self) - 1);. This doesn't traverse the entire structure.

另一方面, list_slice 分配一个新列表,并循环遍历旧列表中的条目,从头到尾-1,将对每个项目的引用复制到新列表中.

On the other hand, list_slice allocates a new list and loops over the entries in the old list ranging from the beginning to the end - 1, copying references to each item to the new list.

如果您要删除列表的最后一个元素,请使用 pop del a [-1] .

If what you're trying to do is remove the last element of the list, use pop or del a[-1].

这篇关于list.pop()和list = list [:-1]之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆