3
s = "0123456789"
print(s[2:-1:-1])

according to me, output of the above question should be "210" BUT it gives nothing please explain to me how?

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
gj_walia
  • 31
  • 2
  • 1
    Does this answer your question? [Python reverse-stride slicing](https://stackoverflow.com/questions/5798136/python-reverse-stride-slicing) – ggorlen Nov 24 '19 at 07:36
  • `print(s[2::-1])` can give you `210`. Which means `seq[low::stride] # [seq[low], seq[low+stride], ..., seq[-1] ]` from [here](https://stackoverflow.com/a/509377/2767755). – Arup Rakshit Nov 24 '19 at 07:37
  • @ggorlen This is not the exact duplicate, as it is not telling why the output is `210`. – Arup Rakshit Nov 24 '19 at 07:39
  • The output isn't 210 though. I think it's a helpful link even if it doesn't get closed out. If I can read [this](https://github.com/python/cpython/blob/master/Objects/sliceobject.c) I'll post an explanation. – ggorlen Nov 24 '19 at 07:49

1 Answers1

3

Syntax: sequence [start:stop[:step]]

  • start:
    • Optional. Starting index of the slice. Defaults to 0.
  • stop:
    • Optional. The last index of the slice or the number of items to get. Defaults to len(sequence).
  • step:
    • Optional. Extended slice syntax. Step value of the slice. Defaults to 1.
+---+---+---+---+
|-4 |-3 |-2 |-1 |  <= negative indexes
+---+---+---+---+
| A | B | C | D |  <= sequence elements
+---+---+---+---+
| 0 | 1 | 2 | 3 |  <= positive indexes
+---+---+---+---+
 |<- 2:-1:-1 ->|      <= extent of the slice: "ABCD"[2:-1:-1] (won't work)

Explanation:

Here in my example "ABCD"[2:-1:-1] If we interpret it, then it says:

  1. start from index 2. (include that item)
  2. Go till index -1 (exclude that item) which is the last item as you can see the table above.
  3. With steps of -1 which basically means in reverse direction. Here you are contradicting your sequence. So it returns nothing.

So the solution would be "ABCD"[2::-1] as someone correctly answered in the comment. This says start from index 2 go till end either beginnig or end based on the steps which is -1 here so beginning.

So same answer to your question print(s[2::-1]) will print 210

Amit Mondal
  • 329
  • 3
  • 10