I’m new to python, and while reading about slice notation, I came across the following code snippet. I was able to understand and use it in very simple examples, but I wasn’t able to grasp its usage in the following example. Any explanation will really help!
>>> a = [1,2]
>>> a[1:1] = [3,4,5]
>>> print a
[1, 3, 4, 5, 2]
>>> a = [1,2]
>>> a[0:1] = [3,4,5]
>>> print a
[3, 4, 5, 2]
and you could read this as “replace
a[n:m]withb” (sincea = a[:n] + a[n:m] + a[m:]).*actually slicing mutates the list in-place (that is,
id(a)remains unchanged) which will usually be preferable (wheras settinga=creates our newaat a different memory location).So in your examples: