I understand that the [start:end] notation means the first number is the position in the list where the slicing start and the last number is the position -1 in the list where the slicing ends, but in this example
U= [2, 'haha', [5,6,9], 3, 2, 1] ;
U[1:2]=[] ;
U[2:]=[] ;
The resulting slice is:
U= [2, [5,6,9]]
Why is this the answer? I get that in the second step 3,2,1 gets eliminated. But why is the resulting slice [2,[5,6,9]] and not [5,6,9]
Python list slices can be replaced by iterables.
You start with this:
U = [2, 'haha', [5,6,9], 3, 2, 1] ;
U[1:2]
is 'haha'
(From element 1
up-to-but-not-including 2
), so replacing that with an empty iterable []
essentially removes 'haha'
from the list.
At that point, you have [2, [5,6,9], 3, 2, 1]
.
U[2:]
is from element index 2
to the end, which is [3, 2, 1]
. Again, as before, setting this to the empty iterable []
, deletes these three elements, leaving [2, [5,6,9]]
Using the python console may make the example easier to understand:
>>> U = [2, 'haha', [5, 6, 9], 3, 2, 1]
>>> U
[2, 'haha', [5, 6, 9], 3, 2, 1]
Get rid of second element.
>>> U[1:2]=[]
>>> U
[2, [5, 6, 9], 3, 2, 1]
Get rid of everything past the second element.
>>> U[2:] = [];
>>> U
[2, [5, 6, 9]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.