Python list slice syntax used for no obvious reason

后端 未结 5 2043
心在旅途
心在旅途 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 17:32

    As it has already been answered, I'll simply add a simple demonstration:

    >>> a = [1, 2, 3, 4]
    >>> b = a
    >>> c = a[:]
    >>> b[2] = 10
    >>> c[3] = 20
    >>> a
    [1, 2, 10, 4]
    >>> b
    [1, 2, 10, 4]
    >>> c
    [1, 2, 3, 20]
    

提交回复
热议问题