Python list slice syntax used for no obvious reason

后端 未结 5 2046
心在旅途
心在旅途 2020-11-27 17:00

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

newList = oldList[:]

Surely this is just the same as:



        
5条回答
  •  忘掉有多难
    2020-11-27 17:23

    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.

提交回复
热议问题