Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding negative slice step value [duplicate]

Tags:

python

slice

I am having a problem in understanding what happens when i put negative value to step in case of slicing.

I know [::-1] reverses a string. i want to know what value it assign to start and stop to get a reverse.

i thought it would be 0 to end to string. and tried

f="foobar"

f[0:5:-1]---> it gives me no output. why?

and i have read start should not pass stop. is that true in case of negative step value also?

can anyone help me to clear my doubt.

like image 757
shubendrak Avatar asked Sep 10 '26 13:09

shubendrak


1 Answers

The reason why f[0:5:-1] does not generate any output is because you are starting at 0, and trying to count backwards to 5. This is impossible, so Python returns an empty string.

Instead, you want f[5:0:-1], which returns the string "raboo".

Notice that the string does not contain the f character. To do that, you'd want f[5::-1], which returns the string "raboof".


You also asked:

I have read start should not pass stop. is that true in case of negative step value also?

No, it's not true. Normally, the start value shouldn't pass the stop value, but only if the step is positive. If the step is negative, then the reverse is true. The start must, by necessity, be higher then the stop value.

like image 84
Michael0x2a Avatar answered Sep 12 '26 01:09

Michael0x2a