1

I'm trying to understand the logic behind reversing a slice using slice index and step.

First of all, I can reverse a string using the slice step like this:

a = "Hello"
a[::-1]
>>> 'olleH'

Also, I can reverse only a part of the string like this:

a = "Hello"
a[:2:-1]
>>> 'ol'

But when I try to reverse the string using another range like this:

a = "Hello"
a[1:3:-1]
>>> ''

I get an empty string.

However, if I inverse the ranges like this example:

a = "Hello"
a[4:1:-1]
>>> 'oll'

I get the reversed slice between indexes 1 and 4.

But, correct me if I'm wrong, I know that the first index from a slice must be less than the second index.

This is why when I run this example:

a = "Hello"
a[4:1]
>>> ''

I get an empty string.

So, can somebody explain to me why reversing a string (slice) while an inversed range with a negative step works, and using the logic of the first index being less than the second one in a slice will give an empty string.

Thanks for your answers.

kbunarjo
  • 1,277
  • 2
  • 11
  • 27
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43

2 Answers2

4

It is not the case that the first number has to be less than the second, it just is the starting index, while the second is the ending index. Therefore, when you are going backwards (third index is -1), the starting index should be larger than the ending index, otherwise you'll get an empty string.

kbunarjo
  • 1,277
  • 2
  • 11
  • 27
3

The syntax is

a[begin;end;step]

So when you use step -1 it will traverse through the string backwards and thus begin should be bigger than the end.

If you omit step it defaults to 1 and will traverse through the string forward and should begin must be smaller than the end.

Fun fact, you can also traverse in steps of -2

a = 'Hello, world!'
a[::-2] # => '!lo olH'
akuhn
  • 27,477
  • 2
  • 76
  • 91