0

"The slice operator creates a new list and the assignment makes t refer to it, but none of that has any effect on the list that was passed as an argument".

But why it is so? Could you explain it to me? I just don't understand.

def bad_delete_head(t) :
    t = t[1:]

letters = ['a', 'b', 'c']
bad_delete_head(letters)
print(letters)

Output: ['a', 'b', 'c']

  • Because you're assigning the result to a local variable, not the caller's variable. – Barmar Mar 31 '22 at 17:55
  • 1
    If you did `t = 0` that wouldn't affect the variable `letters`. – Barmar Mar 31 '22 at 17:56
  • @Barmar It's still not clear. I'm very beginner. But thank you anyway. – Ilia Korepanov Mar 31 '22 at 18:00
  • "But why it is so? " because none of those things mutate the list. Assignment to a variable *never* mutates, so `x = []; y = x; y = [1,2]; print(x)` will still print `[]` not `[1, 2]` – juanpa.arrivillaga Mar 31 '22 at 18:21
  • I suggest reading this: https://nedbatchelder.com/text/names.html for establishing a basic mental model of how variables work in Python. Variables are just *names that refer to objects*. Like a name tag. If I say `x = []` I am saying "create an empty list, and put the name tag "x" on it". Then if I do `y = x`, I'm saying "put the name tag "y" on the object being referenced by the name tag "x"". Then if I do `y = [1, 2]` I'm again just saying "create a new list [1, 2] and move the name tag "y" on to this list", but moving the name tag won't affect the original object – juanpa.arrivillaga Mar 31 '22 at 18:22
  • @juanpa.arrivillaga, thank you very much! I’ll read this article. – Ilia Korepanov Apr 05 '22 at 07:11

0 Answers0