0
>>> num_list = list(range(5))
>>> print(num_list)
[0, 1, 2, 3, 4]

slicing will return all elements except element of index 0. In delete_head() function, x will be reference for a list. x[1:] will return [1,2,3,4] and this value will be assign to x

    >>> def delete_head(x):
        x = x[1:]   

>>> delete_head(num_list)

But function is not working

>>> print(num_list)
[0, 1, 2, 3, 4]

But, even I don't use return statement this function is working:

>>> def d(u):
    del u[0]
>>> r = [1,2,3]
>>> d(r)
>>> print(r)
[2, 3]
  • 1
    Your function `delete_head` does not modify `num_list` in place and it does not return anything. – It_is_Chris Jul 07 '21 at 13:43
  • 1
    `x` is a local variable. Assigning to `x` does *not* affect the list that `x` referred to *before* the assignment. – chepner Jul 07 '21 at 13:44
  • 1
    `def delete_head(x): x.pop()`. You need to *mutate* the list referenced by `x`, not assign to `x`. – chepner Jul 07 '21 at 13:44
  • 1
    @chepner `pop()` removes the last item by default, should be `pop(0)`. – Guy Jul 07 '21 at 13:47
  • `del` is *mutating the list object*. There’s only one object visible inside and outside the function which is being *mutated*. The slicing and assigning to a local variable on the other hand does *not mutate* the object, it creates a new one. – deceze Jul 08 '21 at 05:09

0 Answers0