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()]
?