0

What is the start and stop value when we are doing [::-1] for any sequence? I know it will reverse the string. But want to understand how it is implemented. s[:] - for this start is 0 and stop is len(s).

So how is it working for s[::-1]

Can somebody please explain how it is implemented?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user2550098
  • 163
  • 1
  • 13
  • But what do you mean *"how it is implemented"*? In the CPython behind the scenes? Or if you mean why is `s[:]` equivalent to `s[0:len(s)]` then: because they're the defaults, per the spec. – jonrsharpe Mar 30 '17 at 18:22
  • I don't think that's an appropriate duplicate. This question is trying to understand the start and stop values for `::-1`. The other question doesn't say anything about that, and the obvious values don't work. – user2357112 Mar 30 '17 at 18:26
  • @jonrsharpe if s[::-1] is reversing the string, then why s[0::-1] not reversing the string. – user2550098 Mar 31 '17 at 10:23
  • @user2357112 Thanks. I searched in stackoverflow, did not find my question. so posted it – user2550098 Mar 31 '17 at 10:24
  • @jonrsharpe [x:] is [x:len(s)] i think, not [x:x+1].. so s[::] and s[0::] are same. So why are they behaving different when we give a negative step. – user2550098 Mar 31 '17 at 10:43
  • If you give a reverse step *starting from the first character*, what's the next character? `s[-1::-1]` works, or `s[len(s)::-1]`. Please, again, [edit] to clarify what is confusing you, and spend some time reading the linked question to better understand the syntax. – jonrsharpe Mar 31 '17 at 10:51

1 Answers1

0

In terms of "where does it start" and "where does it stop", it starts at the last element and stops at the first. I think you knew that already, though.

In terms of "what actual start and stop values does the sequence receive", the start and stop are actually None. Any omitted slice argument is implicitly None, so

s[::-1]

is equivalent to

s[None:None:-1]

The sequence will interpret None appropriately depending on the slice direction.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • If it is None then how it is reversing the sequence and why s[0::-1] not reversing the sequence. In stead it is giving first element as output. – user2550098 Mar 31 '17 at 10:39
  • @user2550098: You're telling it to start at the first character and go backwards with `s[0::-1]`. It's not going to find anything but the first character. As for how `s[::-1]` reverses it when the `start` and `stop` arguments are `None`, the sequence interprets `None` values of `start` and `stop` as starting at the last character and stopping at the first when the step is negative. – user2357112 Mar 31 '17 at 15:33