I just encountered this bug:
def fn_that_uses_a_list(list):
if (list[-1] < 0): list += [0]
for item in list:
print(item)
l = [-4, -2]
fn_that_uses_a_list(l)
# Now suddenly l has three items.
However, if I change list += [0]
to list = list + [0]
, then things work. I find this confusing, but it could be because I'm new to Python.
Why is there a difference in this case? I'm looking for a more existential answer, rather than "list
is a reference so +=
modifies the original"
Am I doing something "un-pythonic" that's causing me to run into the bug?
Not sure what you are after, if I use both
list += [0]
andlist = list + [0]
I get the same result.That said,
+=
mutates the list, while+
creates a new list. Try: