Home  >  Q&A  >  body text

python - a=[1,2,3,4,5],b=a和b=a[:],有区别么?

ringa_leeringa_lee2742 days ago972

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-18 09:25:15

    You call it

    b.append(6)
    print (a, b)

    You can see the difference:

    • The former passes the reference

    • The latter is a copy

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 09:25:15

    • b=a 會讓 b 參考到 a Reference object

    • a[:] 會製造一個 a 的副本, 所以 b=a[:] 會讓 b 參考到這個副本, 也就是說 ba Now refer to different objects, but these two objects are equal ( not the same but equivalent )

    This is why on the surface there seems to be no difference between the two, but if it is the former, we have changed ba Both will be affected because they refer to the same object, but the latter does not affect each other because they refer to different objects. . @hsfzxjy's example is to point this out, and you can learn the difference by doing experiments.


    Questions I answered: Python-QA

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:25:15

    Python has a function called id that can get the address of an object. It will be clear if you print it out. Direct = is reference assignment, referencing the original object; and [:] is re-derivation, which will generate a new object

    a=[1,2,3,4,5]
    b=a
    c=a[:]
    print id(a),id(b),id(c)

    reply
    0
  • Cancelreply