I know how thew syntax works for this, but I would like to know the process of how python replaces and alters the list on the left hand side. Ex.
L = [0, 1, 2, 3, 4]
L[0:2] = [5]
print L #L is now [5, 2, 3, 4]
How does python go about this?
This is accomplished with the __setitem__
or __setslice__
methods. (__setslice__
is deprecated IIRC and removed in python3.x).
For a list, the expression:
L[start: stop] = some_iterable
Will take the items from some_iterable
and replace the elements at indices from start to stop (non-inclusive). So, in your demo code, you have:
L[0:2] = [5]
This takes the elements at index 0
and 1
and replaces them with 5
.
Note that the replacement list doesn't need to be the same length as the the sublist that it is replacing.
Perhaps a better way to think of it is as an in-place way to do the following:
L[a:b] = c
# equivalent to the following operation (done in place)
L[:a] + list(c) + L[b:]
If you're actually curious about how it happens, the source code is the best reference. PyList_SetSlice calls list_ass_slice which turns the iterable on the right hand side into a sequence (tuple
or list
IIRC) . It resizes the array to hold the proper amount of data, copies the stuff on the right of the slice into the proper location and then copies in the new data. There are a few different code paths (and orders of operations) depending on whether the list grows or shrinks, but that's the basic gist of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With