+ 2

What is the difference between "+=" and "=+"?

Why is the output of this code 18? def f(x=[]): x+=[3] return sum(x) print (f()+f()+f()) But the output of this code is 9? def f(x=[]): x=x+[3] return sum(x) print (f()+f()+f())

26th Jan 2020, 11:10 AM
Shamil Erkenov
Shamil Erkenov - avatar
7 Antworten
+ 5
There's a conceptional difference between x+=y and x = x+y. The idea is that += changes 'this very object', while the other way creates a separate object. How exactly this plays out - as often in Python - depends on how the type itself is defined. With lists, += is basically synonymous with the method 'extend'. It changes that very object in place, adding another list to the end of it. Now in this version... def f(x=[]): x+=[3] return sum(x) ... the default list x stays the same, so it will still be the same list next time you call the function - stuff from last call still in it. Which means that it will grow each time you call the function. However in this version... def f(x=[]): x=x+[3] return sum(x) ... you create a *new* object x+[3], and then paste the name x to it. So x doesn't refer to the default object anymore - that one still exists, but it isn't influenced by what you do using the name x anymore. So this time, you have a new list, just with a 3 in it, each call.
26th Jan 2020, 11:50 AM
HonFu
HonFu - avatar
+ 4
=+ ? it is just an assignment operator: = where + does not do anything. +6 == 6
26th Jan 2020, 11:22 AM
Seb TheS
Seb TheS - avatar
+ 2
So, x+=[3] and x=x+[3] should have the same output?
26th Jan 2020, 11:29 AM
Shamil Erkenov
Shamil Erkenov - avatar
+ 2
Maybe in this context it is also worth mentioning that it is better to avoid empty iterables as default arguments. better use def f(x=None): if x is None: x=[] # some code... that way it is garantied that an empty list is assigned to x.
27th Jan 2020, 6:17 PM
Harald
+ 2
Absolutely good to mention it. Default lists are a good way to get accustomed to the whole reference issue which in Python you have to understand but can't see. However probably most tutorials at some point warn: Don't do this in real life!
27th Jan 2020, 6:25 PM
HonFu
HonFu - avatar
+ 2
=+ would be just the assignment operator =. The + would be referring to a positive number/expresion relating to the right hand side operand.
28th Jan 2020, 12:44 AM
Sonic
Sonic - avatar
+ 1
Шамиль Эркенов Yes, but lists, and maybe some other iterables have a weird exception with it.
26th Jan 2020, 11:33 AM
Seb TheS
Seb TheS - avatar