简体   繁体   中英

Confusing simple python list behavior with +=

list4=[7,8]
def proc3(mylist):
    mylist+=[9]


print list4
proc3(list4)
print list4

Why does this code produce the answers [7,8] and [7,8,9]? I expected [7,8] and [7,8]. Doesn't mylist+=[9] concatenate the number 9 and create a new list as a local variable only? Why does the "print list4" after the running proc3(list4), but outside the procedure, not result in the original list? I must be missing something obvious here. Thanks in advance for any help.

+= does not return a new list object. Instead, it modifies the original list object in-place.

In other words, this line inside proc3 :

mylist+=[9]

is modifying the list object referenced by mylist . As a result, it is no longer [7, 8] but [7, 8, 9] .

Quoting this answer in another post:

Everything is a reference in Python. If you wish to avoid that behavior you would have to create a new copy of the original with list() . If the list contains more references, you'd need to use deepcopy() :

Let's:

list4 = [7, 8]
def proc3(mylist):
    print id(list4)
    mylist += [9]
    print id(list4)


print list4
print id(list4)
proc3(list4)
print id(list4)
print list4

This would print:

[7, 8]
36533384
36533384
36533384
36533384
[7, 8, 9]

So as you can see, it's the same list in every moment.

the += operator modifies the object. Notice that

x += y

is much different from

x = x + y

(check with your test code)

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