2

I learned that list slicing returns a new list instance. So I think this code wouldn't work, since b[:] is different to b instance. However, the result is 5, and it means list second copied list first. I'm confused about slicing. Doesn't it return a new instance?

def copy(a,b):
        b[:] = a[:]

first = [1, 2, 3, 4, 5]
second = []
copy(first,second)
print second[-1]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • Related: http://stackoverflow.com/questions/10155951/what-is-the-difference-between-slice-assignment-that-slices-the-whole-list-and-d – Caramiriel Mar 08 '15 at 15:41
  • By doing `b[:] = something` you are *updating* the list object `b` references. This works because lists are mutable. So in your function, the (empty) list object created assigned to `second` is updated. – poke Mar 08 '15 at 15:44

1 Answers1

1

You are using slice assignment here:

b[:] = a[:]

Contents of b from start to end is replacing with contents of a.

ndpu
  • 22,225
  • 6
  • 54
  • 69