Home > other >  Was wondering when and why it produces empty strings
Was wondering when and why it produces empty strings

Time:12-11

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)

CodePudding user response:

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.

CodePudding user response:

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.

  • Related