+ 6

What's Happening in this Code! Can anyone explain this correctly???

x=[3,6,8,5,4,10] print(x[0:4:]) print(x[0:4:-1]) output: [3,6,8,5] output:[] I thought the 2nd code output is Reverse of 1st code. How is Empty list possible here?? can anyone explain me???

30th Oct 2017, 4:59 PM
Shadow Windster
Shadow Windster - avatar
3 Answers
+ 1
In the second print function, it will counts backwards i.e., before the 0th element But there is no element before 0th element, so it returns an empty list
14th Nov 2017, 5:00 AM
#RahulVerma
#RahulVerma - avatar
+ 9
Actually, slicing the list can accept three parameters very similar to range() and alike. Those are: Start, Stop and Step. Slicing begins at Start, ends *before* (not including) Stop and skips elements with a Step. However, apart from positive, all three can accept negative numbers, too. For Start and Stop -x means the x-th last element (-1 is last, -2 is second to last, etc.) While for Step this means counting backwards. This is introduced for making it possible to slice not only left-to-right, but also right-to-left -- and naturally, if the Step is negative, Start has to be greater than Stop in order not to become an empty set. Examples: a = [1, 2, 3, 4, 5, 6] a[0:4:2] == [1, 3] (Start from element [0], Stop before [4] and skip each second element) a[4:1:-1] == [5, 4, 3] (Start from element [4], Stop before [1] and count backwards) a[0:4:-1] == [] (Start from element [0], Stop before [4] and count backwards - there are no elements "backwards" from [0])
30th Oct 2017, 7:06 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
print(x[3:0:-1]) output: [5,8,6] so I'm thinking your [0:4:-1] yields [] because there isn't anything before 0. I don't know Python so I might be wrong, but it seems logical to me.
30th Oct 2017, 5:53 PM
John Wells
John Wells - avatar