+ 1

List slicing

list = [0, 1, 2, 3, 4, 5] print(list[4:2:1]) print(list[-2:2:1]) print(list[2:4:-1]) print(list[4:4:-1]) Please explain why all of these print an empty list

9th Sep 2016, 4:35 AM
Eunjae Lee
Eunjae Lee - avatar
2 Respostas
+ 2
First, lets have a closer look at this expression x:y:z, and understand which component stands for. x is the start y is finish which is not included(it means that there will be no element with 'y' index in resulting list) z is the step to walk from x to y. Both x and y may be positive or negative: imagine we have list [0,1,2,3,4,5]. How to understand which element has index -1? Write your list twice and start with second copy: '0' in second copy has 0 index, go left - here is '5' from first copy, decreasing '0' index by one makes it -1 for '5'. [0, 1, 2, 3, 4, 5][0, 1, 2, 3, 4, 5] -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 z may also be negative or positive. Negative means that you need to go down from 'x' to 'y'. Positive - up from 'x' to 'y'. In first case we need x + z > y for non empty list in the result, as x + z < y in second case. Considering your questions: 1. 4:2:1. x=4, y=2, z = 1, z > 0 so we need x+z < y, which is 4+1 < 2 for non empty list. This statement is false and list is empty 2. -2:2:1. '-2' index is the same as '4' for our list, so it is case 1. and empty list again. 3. 2:4:-1. x =2, y=4, z= -1. z < 0, lets have a look if x + z > y is true: (2 + -1 > 4) is false so list is empty. 4. 4:4:-1. z < 0, (4 + -1 > 4) is false, again empty list
9th Sep 2016, 5:43 AM
Textobot
Textobot - avatar
0
Thanks! That was very helpful.
9th Sep 2016, 8:57 AM
Eunjae Lee
Eunjae Lee - avatar