+ 1
I can't understand what's wrong with this code please help me
5 Answers
+ 5
try [::-1] instead of [:-1]
+ 4
P A Arrchith Iyer
Sure, no problem.
There is a thing called index slicing. In normal indexing we only use one value list[2].
But in index slicing such as list[2:4] or list[0:2:1] we use two to three values.
Index slicing arguments:
--> [start : end : step]
Default Values:
--> start = 0
--> end = length of the string
--> step = 1
When a value is not specified, it will use the default value.
For example:
đš list[:3] is also list[0:3]
đš list[:] will simply get all the elements
The third argument is the step. For example, if it's value is 2, it will get elements every two steps.
đ¸ lst = [1, 2, 3, 4, 5, 6]
đ¸ lst[::2]
đš the output would be [1, 3, 5]
But if it is negative it will get the elements from last to first (backwards)
đ¸ lst = [1, 2, 3, 4, 5, 6]
đ¸ lst[::-2]
đš the output would be [6, 4, 2]
And if the value of step is only 1 and it is negative, it will simply get the reverse of that list.
đ¸ list[1, 2, 3, 4, 5]
đ¸ list[::-1]
>> [5, 4, 3, 2, 1]
+ 2
Thanks noteve it is working
+ 2
Can you explain how it works?
+ 2
Thank you so much noteve