Why + And += Is Different?
Solution 1:
Just Try this:
x = [] # empty list
x += "hello"# iterates over the string and appends to listprint(x) # ['h', 'e', 'l', 'l', 'o']
versus
x = [] # empty listx = x + "hello"# TypeError: can only concatenate list (not "str") to list
The +=
operator invokes the __ iadd__()
list method, while +
one invokes the __ add__()
one. They do different things with lists.
+=
adds a number to a variable, changing the variable itself in the process (whereas + would not).
Solution 2:
There is a lack of symmetry here. When using a list
, x += y
is basically x.extend(y)
and extend
works with any iterable.
extend(self, iterable, /)
Extend list by appending elements from the iterable.
But x = x + y
is more restrictive. If x
is a list, y
must be a list also. The list.__add__
method knows the size and structure of both objects, so it can create the new list
efficiently. I'm not sure why the implementers didn't keep these same restrictions for augmented addition. But its easy to turn __iadd__
into an extend
and the functionality is cool.
As for [1,2,3] + 1,
, this expression creates a tuple but it fails on the first element. Had this been an operation that doesn't fail, you'd get the tuple.
>>> [1,2,3] + [4],
([1, 2, 3, 4],)
Post a Comment for "Why + And += Is Different?"