List __iadd__, + = and return value
I noticed some strange behavior with return values of list expansion.
I read this thread Why does + = behave unexpectedly in lists?
but that still doesn't make sense.
This is what I did:
Python 3.5.2 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1, 2]
>>> print(l.extend([1]))
None
>>> print(l.__iadd__([1]))
[1, 2, 1, 1]
>>> print(l += [1])
File "<stdin>", line 1
print(l += [1])
^
SyntaxError: invalid syntax
>>>
I understand that it extend
does not return an extended object as well None
. Not helpful, but I understand.
Now __iadd__
behaves differently, which is odd since I read that it is basically the calls to expand for the list.
But the third one puzzles me. I thought that +=
is the shorthand for __iadd__
, so why can I get SyntaxError
here? Moreover, it __iadd__
returns a modified list, which makes sense to pass as a return value. But I can't seem to use +=
(or *=
if that's the case, for example integers) in function calls.
Is it by design?
source to share