Python why would you use [:] over =

前端 未结 4 1075
隐瞒了意图╮
隐瞒了意图╮ 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:15

    They have the same value, but there is a fundamental difference when dealing with mutable objects.

    Say foo = [1, 2, 3]. You assign bar = foo, and baz = foo[:]. Now let's say you want to change bar - bar.append(4). You check the value of foo, and...

    print foo
    # [1, 2, 3, 4]
    

    Now where did that extra 4 come from? It's because you assigned bar to the identity of foo, so when you change one you change the other. You change baz - baz.append(5), but nothing has happened to the other two - that's because you assigned a copy of foo to baz.

    Note however that because strings are immutable, it doesn't matter.

提交回复
热议问题