2

I understand we pass reference of an object during argument passing in Python.

So,

def changer(b):
    b[0] = "spam"

l = [1,2]
changer(l)             # l is now ["spam",2]

However, if I do,

changer(l[:])          # l remains [1,2]

What is passed to the function in the second case when I pass list slice?

user3267989
  • 299
  • 3
  • 18
  • 4
    You will pass a copy of `l` in the second example. – Selcuk May 10 '16 at 14:41
  • Note that this behavior isn't exclusive to function calls. You can see the same thing happen if you do `l = [1,2]; b = l[:]; b[0] = "spam"; print(l); print(b)` – Kevin May 10 '16 at 14:42

1 Answers1

1

l[:] creates a copy. See slicing. The copy is passed into the function and the function modifies the copy of l. Therefore, l will remain the same.

All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list.

mattsap
  • 3,790
  • 1
  • 15
  • 36
  • 2
    I'd change "splicing" to "slicing." When you splice a list, you usually edit it in-place, removing the spliced section. When you slice a list, you leave the original list untouched. This is also consistent with the `slice` built-in. – Jared Goguen May 10 '16 at 14:50
  • Good point...Thanks. – mattsap May 10 '16 at 14:53