Augmented assignment doesnt rebind mutable data types

Augmented assignment operators (+= and *=) rebind when used with an immutable data type, but don't rebind when used with a mutable data type, such as a list. When used with a list, += is the equivalent of the extend() method; it adds items to the end of a list. So if we rewrite the function to use augmented assignment, the function extends mylist (which is mutable) by adding the argument to the end of the list:

>>> def f(q, mylist=[]): ... mylist += q ... return mylist

Was this article helpful?

0 0

Post a comment