Asic Chen Asic Chen - 1 year ago 69
Python Question

Function which removes the first item in a list (Python)

I am trying to write a function which removes the first item in a Python list. This is what I've tried. Why doesn't remove_first_wrong change l when I call the function on it? And why does the list slicing approach work when I do it in the main function?

def remove_first_wrong(lst):
lst = lst[1:]

def remove_first_right(lst):

if __name__ == '__main__':
l = [1, 2, 3, 4, 5]

l_2 = [1, 2, 3, 4, 5]

# Why does this work and remove_first_wrong doesn't?
l_3 = [1, 2, 3, 4, 5]
l_3 = l_3[1:]

Answer Source

Slicing a list returns a new list object, which is a copy of the original list indices you indicated in the slice. You then rebound lst (a local name in the function) to reference that new list instead. The old list is never altered in that process.

list.pop() on the other hand, operates on the list object itself. It doesn't matter what reference you used to reach the list.

You'd see the same thing without functions:

>>> a = [1, 2]
>>> b = a[:]  # slice with all the elements, produces a *copy*
>>> b
[1, 2]
>>> a.pop()  # remove an element from a won't change b
>>> b
[1, 2]
>>> a

Using [:] is one of two ways of making a shallow copy of a list, see How to clone or copy a list in Python?

You may want to read or watch Ned Batchelder's Names and Values presestation, to further help understand how Python names and objects work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download