Search code examples
pythonlistshallow-copy

Python list slice syntax used for no obvious reason


I occasionally see the list slice syntax used in Python code like this:

newList = oldList[:]

Surely this is just the same as:

newList = oldList

Or am I missing something?


Solution

  • Like NXC said, Python variable names actually point to an object, and not a specific spot in memory.

    newList = oldList would create two different variables that point to the same object, therefore, changing oldList would also change newList.

    However, when you do newList = oldList[:], it "slices" the list, and creates a new list. The default values for [:] are 0 and the end of the list, so it copies everything. Therefore, it creates a new list with all the data contained in the first one, but both can be altered without changing the other.