0

The += operator does an odd list assignment.

This is for a home project. I'm running on Ubuntu and using Python 3.x.

When using += I get this unexpected behaviour:

class foo:
    def __init__(self, arg=[]):
        self.arg = arg

x = foo()
for _ in range(100):
    x.arg += [foo()]

x.arg == foo().arg
# True

And when I don't:

class foo:
    def __init__(self, arg=[]):
        self.arg = arg

x = foo()
for _ in range(100):
    x.arg = x.arg + [foo()]

x.arg == foo().arg
# False

I expect x.arg == foo().arg, to return False and NOT True in the first case.

Edit:

This might be a duplicate of “Least Astonishment” and the Mutable Default Argument, but why is the x.arg += [foo()] behaviour different from x.arg = x.arg + [foo()]?

tpain
  • 144
  • 6
  • Probably part of the answer, but why is the behaviour using `+=` different? – tpain May 06 '19 at 06:50
  • I think this is *actually* rather a duplicate of [this question](https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists?noredirect=1&lq=1). @tpain try adding a `print(arg)` inside your class's init function and notice how `arg` is *empty* for your second method! Also try printing both `foo().arg` and `x.arg` at the end of both methods, they are only equal in the `+=` case. Also [see here](https://stackoverflow.com/a/43785469/565489) for an easier example. – Asmus May 06 '19 at 07:14
  • Awesome @Asmus, thanks! I agree, this is a duplicate of your linked question(s). – tpain May 06 '19 at 07:29

0 Answers0