I have noticed some strange behaviour with list extension return values.
I have read this thread Why does += behave unexpectedly on lists?
but it still does not 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 extend does not return the extended object, but None. Not helpful, but I get it.
Now __iadd__ behaves differently, which is weird, since I read that this basically calls extend for a list.
But the third one baffles me. I thought += was shorthand for __iadd__, so why do I get a SyntaxError here? Especially since __iadd__ returns the modified list, which would make sense to pass on as a return value. But it seems I can't use += (or *= for that matter, e.g. with integers) in function calls.
Is that by design?
l.__iadd__(val) is a function call, that is, an expression.
l += [1] is an assignment, that is, a statement.
Argument values (the ones you have supplied to print in this case) are not allowed to be statements, only expressions, simple as that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With