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?!
x[:0]is equivalent tox[0:0], both of them are a slice ofxstarting from index0up 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 listyto this slice, as inx[:0] = yor equivalentlyx[0:0] = y, you arere not replacing any elements inxbecause the slice is empty.Instead, you're inserting all elements of
yat the beginning of the list.