简体   繁体   中英

Adding to lists in Python 2.7

>>> A = [1,2,3,4]
>>> D = A
>>> D
[1, 2, 3, 4]
>>> D = D + [5]
>>> A
[1, 2, 3, 4]
>>> C = A
>>> C += [5]
>>> A
[1, 2, 3, 4, 5]

Why does C += [5] modifies A but D = D + [5] doesn't?

Is there any difference between = and += in python or any other language in that sense?

Actually yes there is. When you use += you're still referencing to the same object, however with + you're creating a new object, and with = you reassign the reference to that newly created object. This is especially important when dealing with function arguments. Thanks to @Amadan and @Peter Wood for clarifying that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM