Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why s[0:4:-1] return nothing in Python?

When s = 'abcdefg', s[0:4:-1] and s[1:-1:-1] return nothing in Python3. However, s[:4:-1] returns "gf". Could anyone explain the mechanism behind these two scenarios (especially in terms of memory)?

like image 562
Sid Lin Avatar asked May 20 '26 01:05

Sid Lin


1 Answers

The start is always the first index of the iteration.

The stop is the end-boundary of your iteration.

The step gives an orientation and a step size to the iteration. So the iteration always goes from start to stop in the direction given by the sign of step.

Thus s[start:stop:step] means to take the characters s[start], s[start + step], s[start + 2 * step], ..., and so on until stop is reached.

In other words, s[start:stop:-1] is not equivalent to reversed(s[start: stop]).

Examples

Thus in your example s[0:4:-1], the is step negative so the iteration process immediately stops because the start index is already on the left of stop.

a b c d e f g h
0 1 2 3 4 5 6 7
^       ^
s       s
t       t
a       o
r       p
t

<-------- orientation

On the other end, if you were to try s[4:0:-1], you would get 'edcb' (remember that the stop index is excluded).

a b c d e f g h
0 1 2 3 4 5 6 7
^       ^
s       s
t       t
o       a
p       r
        t

<-------- orientation

Finally, leaving start empty means from the end of the string. This is why you see all characters from the end to index 4 in reverse.

a b c d e f g h
0 1 2 3 4 5 6 7
        ^     ^
        s     s
        t     t
        o     a
        p     r
              t

<-------- orientation
like image 128
Olivier Melançon Avatar answered May 22 '26 14:05

Olivier Melançon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!