+ 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]

9th Jan 2019, 4:17 PM
Md. Tanvir Ahmed
Md. Tanvir Ahmed - avatar
6 Antworten
+ 6
Kishalaya Saha oh... then maybe I should say it a virtual index of -1🤔
10th Jan 2019, 4:55 AM
Flandre Scarlet
Flandre Scarlet - avatar
+ 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.
9th Jan 2019, 5:10 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 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)
9th Jan 2019, 10:52 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 1
print(squares[Len(squares)-1:-1:-1]) prints empty lists. don't understand 😐
9th Jan 2019, 5:08 PM
Md. Tanvir Ahmed
Md. Tanvir Ahmed - avatar
+ 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 😂
10th Jan 2019, 2:43 AM
Kishalaya Saha
Kishalaya Saha - avatar
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]
22nd Mar 2019, 8:35 AM
Mauricio De Martino
Mauricio De Martino - avatar