Hi Hari,
The rule for augmented assignment operators such as +=
is that, like
other operators, they call a special “dunder” (double-underscore) method
to allow classes to customise what the operation does.
If the special dunder operation doesn’t exist, then the augmented
assignment falls back on the ordinary operator.
So the operation:
obj += x
turns into something like this in the interpreter:
-
Does obj
have the special method __iadd__
?
-
If so, then run obj = obj.__iadd__(x)
.
-
If not, then run obj = obj + x
.
For integers, there is no special __iadd__
method, and so the +=
operation is just syntactic sugar for n = n + m
. Same for strings.
But lists do define a special __iadd__
method, making it an inplace
concatenation.
For lists, +
does list concatenation:
mylist + x
requires x to be a list, and it returns a new list formed by
concatenating all the items of mylist and the items of x.
mylist = [10, 20]
new = mylist + [30, 40] # Can only add list to list.
print(new)
prints a new list, [10, 20, 30, 40]
while leaving the original mylist
untouched.
But augmented assignment +=
does in-place concatenation:
mylist += x
and x can be any sequence, not just a list, and it concatenates the
items of x to mylist in-place. It does not create a new list.
mylist = [10, 20]
mylist += [30, 40] # mylist is now [10, 20, 30, 40]
mylist += (50, 60) # tuples are okay, not just lists
mylist += "xyz" # strings are sequences too!
print(mylist)
will print [10, 20, 30, 40, 50, 60, 'x', 'y', 'z']
.
So +
and +=
for lists are still concatenation, just slightly
different versions:
-
+
is list-to-list concatenation, and returns a new list
-
+=
concatenates the items of any sequence or iterator to the
existing list, in-place.