Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing and Slicing in Python [duplicate]

Tags:

python

I just started learning programming and I need some clarification.

For

s = "abcdef"
print(s[0:2:-1])

The output is an empty string. What I don't quite understand is why print(s[:2:-1]) has an output of fed, and print(s[0:2:-1]) does not.

like image 266
SmithH Avatar asked Dec 28 '25 22:12

SmithH


2 Answers

print(s[:2:-1]) is not the same as print(s[0:2:-1]) - it's the same as print(s[None:2:-1]). When you leave out one of the slice parameters or use None, the endpoint is substituted. If the step size is negative, the start point is the end of the sequence and the end point is the start of the sequence. print(s[0:2:-1]) goes from s[0] to s[2], but it can't because 2 > 0 and there's no way to count backward from 0 to 2. print(s[:2:-1]) goes from s[-1] to s[2], because s[-1] is the last character of the string.

like image 61
Mark Ransom Avatar answered Dec 31 '25 12:12

Mark Ransom


If you set the third parameter to be negative, the elements of the iterable will be traversed in reverse order. Then letting the first parameter be empty will mean that the iteration should start from the rightmost element. Think about the fact that s[::-1] == 'fedcba'.

like image 39
uniglot Avatar answered Dec 31 '25 10:12

uniglot



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!