0

Need help in python slicing

X = [1, 2, 3, 4, 5, 6] print(x[::-2]) The output should be = [5, 3, 1] But the real output is = [6, 4, 2] It seems like there is an invisible element after 6 Can anybody tell me why is that happened?

24th Oct 2022, 10:40 PM
Mohamed Ehab
Mohamed Ehab - avatar
2 ответов
+ 5
Where did you get what should be [5,3,1]? Reminder: Slice = [From:Before:Step] If you want it to be [5,3,1]: print(x[-2::-2])
24th Oct 2022, 11:19 PM
Solo
Solo - avatar
+ 2
print(x[::-2]) # syntax [start : end : step] in your case you omitted the arguments "start" and "end" so python will treat it as [len(x)-1 : 0 : -2] means print(x[5 :0 : -2]) that's why it's printing [6, 4, 2]
25th Oct 2022, 12:22 PM
Ratnapal Shende
Ratnapal Shende - avatar