2

sorry I'm new to python and still trying to wrap my head around few fundamentals. I know lists are mutable objects in python, but can't understand how the two functions below handle lists, and why one changes the list itself and the other doesn't

def f(x, y):
    x.append(x.pop(0))
    x.append(y[0])
    return x

>>> a=[1,2,3]
>>> b=[1,2]
>>> f(a,b)
>>> [2, 3, 1, 1]
>>> a
>>> [2, 3, 1, 1]

def f(x, y):
    y = y + [x]
    return y

>>> a=[1,2,3]
>>> f(4,a)
>>> [1, 2, 3, 4]
>>> a
>>> [1, 2, 3]

Thank you

Hayley Guillou
  • 3,953
  • 4
  • 24
  • 34
katto ch
  • 109
  • 1
  • 9

2 Answers2

3

The + operation stores the result in a new list, while append operation appends the new value into the existing list

For example,

def f(x, y):
    y = y + [x]
    print(y)
    y.append(x)
    print(y)

a=[1,2,3]
f(4,a)
print(a)

gives

[1, 2, 3, 4]
[1, 2, 3, 4, 4]
[1, 2, 3]

y = y + [x] creates a new list y & hence the change is not reflected to the original list a & also the later append changes the new list y

but

def f(x, y):
    y.append(x)
    print(y)
    y = y + [x]
    print(y)

a=[1,2,3]
f(4,a)
print(a)

output

[1, 2, 3, 4]
[1, 2, 3, 4, 4]
[1, 2, 3, 4]

Here the append operation changes the original list a after that new list y is created

Anupam Ghosh
  • 314
  • 3
  • 10
1

Simply put, the difference is in the function of append and +. append adds a new item to the list without creating a new list. + merges two lists together and creates a new list.

For more information, see DNS's answer here.

Community
  • 1
  • 1
Hayley Guillou
  • 3,953
  • 4
  • 24
  • 34