Difference between list.pop() and list = list[:-1]

Viewed 1509
>>> 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?

6 Answers

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

the pop method returns the last item from the list that it removes. for example:

a = [1,2,3,4]
b = a.pop()
print(b)  # 4

Also, using slicing, you are making a copy of the old list, whereas with using pop the list reference remains the same.

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()

Yes there is difference. when you use a.pop() you remove from list too when you use a[:-1] object list not change check with len(a)

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

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