Why slicing of [:0] does not return an error?

66 Views Asked by At

Why slicing of [:0] does not return an error?

  • Exercise: CHANGE the x list, to include the y list in the beginning, and the x list after it. Do NOT use the "+" operator, nor methods or functions.

Staff Answer:

y = [1, 2, 3]
x = [4, 5, 6]
x[:0] = y
print(x)

Result: [1, 2, 3, 4, 5, 6]

The question is, why isn't x[:0] producing an error? What space is there before x[0]?

Index
0 OR -1 1 2 etc...

I mean, where does it fit?! Is there space BEFORE the first index?!

2

There are 2 best solutions below

2
Luxaaa On

x[:0] is equivalent to x[0:0], both of them are a slice of x starting from index 0 up to (not including) 0. This effectively denotes a segment of the list where no elements are present, hence it results in an empty slice. Therefore, when you assign a list y to this slice, as in x[:0] = y or equivalently x[0:0] = y, you arere not replacing any elements in x because the slice is empty.

Instead, you're inserting all elements of y at the beginning of the list.

0
chepner On

Slice assignment doesn't insert so much as it replaces. You can think of any assignment like

L[x:y] = z

where 0 <= x <= y* as being the same as

L = L[:x] + z + L[y:]

except L is modified in place, rather than a new list being created. In particular,

  • If z is shorter than the target slice, the list becomes shorter
  • If z is longer than the target lice, the list becomes larger

When you assign to x[:0], you "replace" the empty slice at the start of the list with the contents of y, without affecting the elements in x[0:] (i.e., the entire original list.) Using the semantics above, you can say that x[:0] = y is equivalent to x[:0] + y + x[0:] == y + x`, but in-place.


* The semantics can be expanded for arbitrary x and y, but that didn't seem necessary for this answer.