I have encountered the following unexpected behavior when changing values of a slice of a list (by index):
# Expected behavior:
>>> a = [1,2,3,4]
>>> a
[1, 2, 3, 4]
>>> a[2] = 5
>>> a
[1, 2, 5, 4]
>>> a[2:]
[5, 4]
>>> a[2:] = ['y', 2]
>>> a
[1, 2, 'y', 2]
>>> a[1:]
[2, 'y', 2]
>>> a[1:][0]
2
# Unexpected behavior:
>>> a[1:][0] = 'hello'
>>> a
[1, 2, 'y', 2] # I would have expected [1, 'hello', 'y', 2] here
As you can see, you can overwrite the original list by assigning a list to a slice, like in a[2:] = ['y', 2]
. However, if you try to overwrite elements of a slice by index (or by a slice-of-slice construction like >>> a[1:][:1] = [2]
), there is no error, the original list does not get updated however.
Is there a proper way of doing this? Why does Python (3.7.3) behave this way?