0

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?

Soumya
  • 13,677
  • 6
  • 34
  • 49
  • 3
    What is your expected behaviour? Don't you want list to have three items after the function? – syntonym Jun 17 '15 at 18:25
  • What's wrong here !! – Iron Fist Jun 17 '15 at 18:27
  • @syntonym No. I temporarily need a list with three items during the function. I still need the original list to stay the same after calling the function... – Soumya Jun 17 '15 at 18:32
  • Well, using `list` as a variable name is a bit unpythonic to start with. But if it's your *intent* to create a new list, then I'd use a new variable name for that new list in your code: `my_new_list = list + [0] if list[-1] < 0 else list`. That'll prevent you from running into the `+=` trap. OTOH, if it's your intent to modify the incoming list, then it looks like you're getting exactly the behaviour that you want. – Mark Dickinson Jun 17 '15 at 18:32

1 Answers1

0

Not sure what you are after, if I use both list += [0] and list = list + [0] I get the same result.

That said, += mutates the list, while + creates a new list. Try:

def fn_that_uses_a_list(list):
  if (list[-1] < 0):
    print id(list)
    list += [0]
    # list = list + [0]
    print id(list)
  for item in list:
    print(item)

l = [-4, -2]
fn_that_uses_a_list(l)
Ecir Hana
  • 10,864
  • 13
  • 67
  • 117
  • I think the intend was not that the `print`s print something differently, but the mutation of the list takes place. – syntonym Jun 17 '15 at 18:34