2
In [20]: from collections import Counter In [21]: x = [Counter()] In [22]: z = x[0] In [23]: z.update("w") In [24]: z Out[24]: Counter({'w': 1}) In [25]: x Out[25]: [Counter({'w': 1})] In [26]: z += Counter(["q"]) In [27]: z Out[27]: Counter({'q': 1, 'w': 1}) In [28]: x Out[28]: [Counter({'w': 1})] 

I would have expected x to be [Counter({'q': 1, 'w': 1})]. What is happening?

0

1 Answer 1

5

x += y will effect another reference to x only if x has an __iadd__ method. If it has just __add__, x += y is the exact equivalent of x = x + y. collections.Counter is something that does not have __iadd__, but does have __add__. Because of that, z += ... is the same as z = z + ..., and you are just redefining z instead of modifying the object. (I found that out by using help(collections.Counter) and searching for __iadd__. It doesn't have it.)

Sign up to request clarification or add additional context in comments.

1 Comment

Sounds like += is best avoided then. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.