Similar to using this[0] = something
, you can also specify slices:
>>> x = [1, 2, 3, 4]
>>> x[1:3] = [0, 0]
>>> x
[1, 0, 0, 4]
Since slices can have parts left out (the start, stop, or step), you can change the whole list by something like this:
>>> x = [1, 2, 3, 4]
>>> x[:] = [4, 5, 6]
>>> x
[4, 5, 6]
This (as seen above) is capable of changing even the length of the list. As can be seen below, this is indeed changing the actual object, not redefining the variable:
>>> x = [1, 2, 3, 4]
>>> y = x
>>> x[:] = [3, 4]
>>> y
[3, 4]
It doesn't necessarily need to be a list at the right end of the assignment. Anything that is iterable can be on that side. In fact, you could even have a generator:
>>> x = ["1", "2", "3", "4"]
>>> x[:] = (int(y) for y in x)
>>> x
[1, 2, 3, 4]
or the returns of map()
(a list in Python 2; a map
object in Python 3):
>>> x = ["1", "2", "3", "4"]
>>> x[:] = map(int, x)