3

Here's a strange case I came across.

[1] + {2:3}
# raises an error as expected.
a = [1]
a += {2:3}
# a = [1, 2]

No error is raised in the second case. In fact the list now looks like [1, 2]. The culprit is the __iadd__ method which when invoked allows us to add a list and a dictionary. I've been looking at the Cpython source code to figure out where this arises but have had no luck so far (I generally don't know what I'm doing when it comes to Cpython source).

Can someone explain this?

arjoonn
  • 960
  • 1
  • 9
  • 20
  • 4
    `+=` (`__iadd__)` is effectively `list.extend` and `list.extend` takes any iterable which in this case a `dict` (its keys) are... There's a few questions similar to this with answers that explain it in more detail... hold on... :) – Jon Clements Apr 23 '18 at 07:55
  • I would have thought it invokes the `__add__` internally instead of `list.extend`? – arjoonn Apr 23 '18 at 07:58
  • top two answers of the dupe explain it fairly well... – Jon Clements Apr 23 '18 at 07:59
  • @theSage If it invoked `list.__add__` it would create a new list. But `__iadd__` and `extend` modify the original list instead of creating a new one. – khelwood Apr 23 '18 at 08:00
  • Can't add an answer, since the question was closed. But think about it this way: The return type of `[1] + {2: 3}` is unclear, so an error is the right behavior. However, with `+=` it is clear that the right-hand side should be interpreted as a list. – Florian Brucker Apr 23 '18 at 08:00
  • I think the duplicates explain it. My bad. I should have searched more before posting. – arjoonn Apr 23 '18 at 08:02

0 Answers0