What is the difference between reversing a list in place and reversing using slicing in python?

Viewed 39
s[:] = s[::-1]

versus

s = s[::-1]

Please explain the difference between achieving the result using the above methods.

1 Answers

The first mutates the original list itself. The second creates a new list, and assigns it back to the variable.

>>> s = [1,2,3]
>>> id(s)
2186036088200        # original id
>>> s[:] = s[::-1]
>>> id(s)
2186036088200        # still same id
>>> s = s[::-1]
>>> id(s)
2186036085000        # new id, because new list was created

The first method is called "slice assignment".

Related