Python why would you use [:] over =

前端 未结 4 1073
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 04:36

I am just learning python and I am going though the tutorials on https://developers.google.com/edu/python/strings

Under the String Slices section

4条回答
  •  不知归路
    2021-02-05 05:22

    While referencing an object and referencing the object's copy doesn't differ for an immutable object like string, they do for mutable objects (and mutable methods), for instance list.

    Same thing on mutable objects:

    a = [1,2,3,4]
    b = a
    c = a[:]
    a[0] = -1
    print a    # will print [1,2,3,4]
    print b    # will print [-1,2,3,4]
    print c    # will print [1,2,3,4]
    

    A visualization on pythontutor of the above example - http://goo.gl/Aswnl.

提交回复
热议问题