>>> 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?
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.
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.
If what you're trying to do is remove the last element of the list, use pop or del a[-1].
pop do not change the id, just pop one item of list.
[:-1] is slice operation, which create a new list from old list.
>>> a = [1,2,3]
print(id(a))
>>> a.pop()
3
print(id(a))
>>> a
[1, 2]
>>> a = [1,2,3]
>>> a = a[:-1]
>>> a
print(id(a))
[1, 2]
>>>
id output (the number is not important, same or not same is key point):
4470627464
4470627464
4474450952
There is an basic difference thats occurs using in functions . Using[:-1] unchanged the original list but pop() can do.
a = [1,2,3]
b = [1,2,3]
def functionb(list):
list = list[:-1]
return list
def withpop(list):
return list.pop()
functionb(b)
withpop(a)
print b
print a
Will printed:
[1, 2, 3]
[1, 2]
Second is execution time . pop() is faster than [:-1] Because when you use [:-1]you have to overwrite to list.Lets say you have thousands values in index so it will be slowly than pop()
The way you have presented them, there's no outward difference. The pop instruction gives the interpreter an easier time of optimizing the instruction, as it can merely decrement the length attribute of the list. The -1 assignment will construct a new list, assign that to a, and then leave the old one for garbage collection.
There is a huge difference in aliasing: if you assigned something else to that list, you will get side effects with pop. For instance:
>>> a = [1, 2, 3, 4]
>>> b = a
>>> b
[1, 2, 3, 4]
>>> a.pop()
4
>>> b
[1, 2, 3]
>>> a = a[:-1]
>>> b
[1, 2, 3]
>>> a
[1, 2]
popmodifies the list being referenced byain-place in constant timw, whereas using the slice creates a new list and assigns that toaand works in linear time - juanpa.arrivillaga