Reputation: 45
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.
Upvotes: 0
Views: 91
Reputation:
+=
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]
.
Upvotes: 3
Reputation: 10162
the +=
operator modifies the object. Notice that
x += y
is much different from
x = x + y
(check with your test code)
Upvotes: 0
Reputation: 34146
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 usedeepcopy()
:
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.
Upvotes: 1