0

Why res = [0:5:-1] dont work?

I have a list nums = [0, 1, 2, 3, 4] res = nums[ : : -1] means that reverse a list like [4, 3, 2, 1, 0] but why res = nums[0: 5: -1] do not work?

16th Nov 2021, 1:26 AM
Nguyen Le Cong
Nguyen Le Cong - avatar
5 Réponses
+ 6
EXPLANATION OF INDEXING WITH EXAMPLES. In positive indexing ,it moves from start to end(not included)*. *In forward direction* nums = [1,2,3,4,5,6] #examples 1)print(nums[1:4]) Output: [2,3,4] {No of elements = stop-start} 2)print(nums[2:5:2]) Output: [3,5] {A forward jump} In negative indexing ,it moves from start to end (not included)*. *in backwards direction* 1)print(nums[4:0:-1]) Output: [5,4,3,2] {Moving backwards} 2)print(nums[4::-1]) Output: [5,4,3,2,1] {As i didn't mentioned stop it reaches the beginning, compare with above example} Finally remember the points which I represented with * You might use negative numbers for start and stop but remember the movement 1)print(nums[-2:-4]) Output : [] {started from last 2nd number and it will move forward as by default a postive jump of 1 is made ,but the stop is in the back so, you have given wrong, so it doesn't move and returns empty list, as list slicing returns new list without modifying the original list} *nums[::-1] #for reversing
16th Nov 2021, 5:17 AM
Prabhas Koya
+ 6
ANSWER TO YOUR QUESTION print(nums[0:5:-1]) It starts from 0 and tries to move in backward direction to the stop , but your stop seems to be in front of it, so as I mentioned in above explanation it returns [].
16th Nov 2021, 5:23 AM
Prabhas Koya
+ 1
Nguyen Le Cong Because in this case 0 is start index, 5 is end index and -1 is step As you can see you are moving towards lower to higher index but step is -1 so result would be a empty list print(nums[0: 5:2]) Try this you will get [0, 2, 4]
16th Nov 2021, 1:39 AM
A͢J
A͢J - avatar
+ 1
You can try this instead print(nums[-1:-6:-1]) print(nums[::-1])
16th Nov 2021, 5:14 AM
Python Learner
Python Learner - avatar
+ 1
Thank you all very much! I am clearly now!
16th Nov 2021, 7:26 AM
Nguyen Le Cong
Nguyen Le Cong - avatar