0
list = ['a', 'b', 'c', 'd'] print list[1:-1] ## ['b', 'c'] list[0:2] = 'z' ## replace ['a', 'b'] with ['z'] print
plz explain this .
1 Odpowiedź
0
1. indexes in python start from 0, so list[0] = 'a'
2. negative indexes start counting backwards from the last element, that's why list[-1] = 'd'
3. when slicing a list ( print list[1:-1] ), the first position is included and the last is excluded
4. list[1:-1] starts from index 1 which is 'b' and goes to index -2, because the last position mentioned (-1) is excluded ( see point 3 )
5. list[0:2] = 'z' does an assignment to elements on index 0 and 1 ( because of point 3 from above ) with the value 'z'
Cheers