3

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?

Community
  • 1
  • 1
Niko
  • 33
  • 3

2 Answers2

1

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.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • Thanks, I wasn't even aware of the distinction. Very interesting. If anyone else also didn't know, [here's](http://stackoverflow.com/questions/4728073/what-is-the-difference-between-an-expression-and-a-statement-in-python) a good explanation. – Niko Mar 29 '17 at 16:35
  • 1
    @Niko If you're interested in more technical details, Python has 3 full chapters for expressions and simple and compound statements in the [Reference Manual](https://docs.python.org/3/reference/index.html) Might want to bookmark it for some later point :-) – Dimitris Fasarakis Hilliard Mar 29 '17 at 16:39
0

__iadd__ is used to implement +=, but the two are not identical. l += [1] is still a statement, while l.__iadd__([1]) is an expression.

chepner
  • 497,756
  • 71
  • 530
  • 681