0

This is my piece of code and I am wondering why it produces an empty string

xs = "0123456789"

x = xs[4:-5:-1]

print(x)
  • Probably want to read through this: [Understanding slicing](https://stackoverflow.com/questions/509211/understanding-slicing). – sj95126 Dec 10 '22 at 16:52
  • 1
    Do you understand the extended slice syntax in general? What the `4`, `-5`, and `-1` mean individually? – chepner Dec 10 '22 at 16:52
  • A slice `[i:j:k]` means ["slice of s from i to j with step k"](https://docs.python.org/3/library/stdtypes.html#common-sequence-operations). For the slice `[4:-5]` in your case, however, there is no way to step through it with stepsize -1; you can only step from 4 to -5 forward. If you would use, e.g., `[4:-8]`, you can only step backward through it: `[4:-8:-1`] therefore does work, and produces `"43"`. You get an empty string in the first case, because you start at `[4]`, go back, and immediately hit a boundary: there are no (more) characters in that direction. – 9769953 Dec 10 '22 at 16:55
  • @chepner yes I understand 4 is the start of the slice and it includes it while -5 is the end of the slice and it starts from the right side starting with index -1. So if we were to slice it without the step of -1 we would get only 4. But I don't understand how the step makes it an empty string. – Jacob Raymond Dec 10 '22 at 16:55

2 Answers2

2

A negative step doesn't simply reverse the result of a "positively stepped" slice. It affects the condition under which the slice is "terminated".

xs[x:y:-1] consists of xs[k] where x >= k > y. In this case, there is no k that satisfies k > y, because (after adjusting the negative index to its corresponding positive value) x >= y is false. As a result, no elements of the string are used to build the result.


xs[x:-y] == xs[x:len(xs) - y], so

xs[4:-5:-1] == xs[4:len(xs) - 5:-1]
         == xs[4:10-5:-1]
         == xs[4:5:-1]

There is no k such that 4 >= k > 5.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • oh wow, never thought of a negative slice more than it moves it reversed by the number u put there. thank you very much :) – Jacob Raymond Dec 10 '22 at 17:11
0

According to python slicing syntax:

array[start:stop:step] # first element is start index, second is stop index and last is the step.

So, in your case, xs[4:-5:-1] starts with index 4, ends with index -5, and has a step of -1.

If you would have used xs[4::-1], the output would be '43210', but since -5 is not reachable with step of -1, you get an empty array.

  • I don't understand what you mean by not reachable with a step of -1. Without the step, xs[4:-5] you get only '4' but when you apply the step it prints empty. I'm really confused on why – Jacob Raymond Dec 10 '22 at 17:03
  • Because the step determines how the start and stop indices are used, not just the order in which elements from `xs[4:-5]` are presented. – chepner Dec 10 '22 at 17:10