0
def my_append1(list1, item):
    list1 = list1 + [item]
    return

def my_append2(list1, item):
    list1 += [item]
    return

The above two functions give me different results:

test = [1, 2, 3]
my_append1(test, 1)
print(test) ==> [1, 2, 3]

test = [1, 2, 3]
my_append2(test, 1)
print(test) ==> [1, 2, 3, 1]

Why are they different?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
Fihop
  • 3,127
  • 9
  • 42
  • 65
  • 1
    `+=`'s analogue is `extend`, not `append` – roippi Sep 28 '14 at 16:21
  • 2
    Using `+=` is equivalent to `list1.extend([item])`, using `list1 = list1 + [item]` is just rebinding `list1` inside of `my_append1` to a brand new list object in the local scope, which gets thrown away when the function exists. – dano Sep 28 '14 at 16:39

0 Answers0