1

"abcde"[0:5:1] gives abcde. So I expected "abcde"[4:-1:-1] to return edcba but it gives nothing. Is there no way to get same result as "abcde"[4::-1] while explicitly giving middle parameter?

2
  • 1
    Middle section of slice expression is like this: len(obj)-1. In your case abcde[4:4:-1]. Commented Oct 27, 2020 at 3:41
  • Maybe you want something like this: "abcde"[4:None:-1] Commented Oct 27, 2020 at 8:06

5 Answers 5

1

-1 in slicing in Python means: the 4rth (last before last). 4:-1 means then 4:4 -> empty string.

"abcde"[4::-1] # this gives "edcba" "abcde"[4:-(len("abcde")+1):-1] # this too 
Sign up to request clarification or add additional context in comments.

Comments

1

0 | 1 | 2 | 3 | 4

a | b | c | d | e

=============

[4:-1:-1]

 4 -> e -1 -> e -1 -> step back 

=============

=> nothing between index 4 -> -1 with a step back

Comments

0

Python list syntax is:

list[start:stop:step]

In the first example: start=0, stop=5, step=1. This is equivalent to the C style for loop:

for (i=0; i<5; i++)

In your second example, start=4, stop=-1=4, step = -1. This is equivalent to the C style for loop:

for (i=4; i>4; i--)

Since the start and stop conditions are the same, your result is empty.

Since -1 is a negative number, which as a start/stop is a special case in python list slicing that means "len(list)-1", you can't actually do the operation you want:

for (i=4; i>-1; i--)

So instead your best bet is "abcde"[::-1] which will correctly infer the end, and the start, from the direction.

Comments

0

If you need to use a number for the stop position, for example, you are using a variable to represent the stop index, then you can use the negative value equal to -len(obj) - 1 where obj is the object you want to reverse as the position before the first character:

>>> 'abcde'[4:-6:-1] 'edcba' 

or,

>>> 'abcde'[-1:-6:-1] 'edcba' 

Comments

0

You are slicing from the last index (4) to index 4 which results in an empty string. In other words, Python is doing the following:

"abcde"[4:4:-1] # which is equal to "abcde"[4:4] # and evaluates to "" 

If you slice from the last index (4) to the first index (0) with a stride of -1 you can reverse it. Thus the following code would work:

"abcde"[-1:0:-1] 

Which in actual practice can be abbreviated to:

"abcde"[::-1] 

1 Comment

Specifically, "abcde"[0:-1:-1] should be "abcde"[-1:0:-1], which still doesn't work (since it omits "a" by stoppingat index 1 not 0). "abcde"[-1::-1] works fine though, since an empty start or end means "the start or end that makes sense in the context of the stride sign"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.