+ 2
Ambiguity in List Slicing 😕
We know if If the first number in a slice is omitted, it is taken to be the start of the list then why two output is different? squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares[0::-1]) print(squares[::-1]) output: [0] [81, 64, 49, 36, 25, 16, 9, 4, 1, 0]
6 odpowiedzi
+ 6
Kishalaya Saha oh... then maybe I should say it a virtual index of -1🤔
+ 5
my_list[i:j:k]
When i and j are omitted, they are taken to be the "end values". With a positive k, the end value for i is 0 and for j is len(my_list). When k is negative, end value for i is len(my_list)-1, but for j it is to the left of the index zero. (I want to say -1, but that unfortunately has a different meaning.)
Basically when an index is omitted, it tries to get the biggest slice possible. Hope that makes sense. Let me know 😊
Edit: Md. Tanvir Ahmed sorry, I deleted my previous comment because I incorrectly wrote -1 there. Basically when we write a negative number for i or j, it is counted from the right end instead. So it is taken as len(my_list)+i or len(my_list)+j. Thus squares[len(squares)-1:-1:-1]
is the same as squares(len(squares)-1:len(squares)-1:-1], which is obviously empty.
+ 4
list[start:stop:step] = list[slice(start,stop,step)]
start and stop are the index
If they're negative, it counts from back
If start and stop are None, their default values will be (0, len(list)) if step is positive, otherwise (len(list)-1, -1)
+ 1
print(squares[Len(squares)-1:-1:-1]) prints empty lists. don't understand 😐
+ 1
Flandre Scarlet when step is negative, default for stop is not exactly -1, because -1 as stop means len(list)-1. I made that mistake too 😂
0
Its more simple than u think. Just change the 0 place.
squares[0::-1] == squares[0:0:-1]
squares[::-1] == squares[81:0:-1] or squares[:0:-1]