0

I am trying to write my own version of the reversed() function and I don't quite understand how the suggested solution works.

a="sample string"
# my solution
reversed_a=a[len(a):-1:-1] 

#suggested solution
reversed_a=[::-1] 

Shouldn't [::] mean [0:len(a)]? If so, how does it work then? I though it would go from 0 to len(a) with a step of -1 and raise an exception due to the negative index value.

Alex.Kh
  • 572
  • 7
  • 15
  • General observation. If you mention *suggested solution*, you should indicate where it was suggested. – SergeyA Sep 20 '19 at 18:46
  • @DeepSpace Unfortunately, the duplicate does not **explain** why begin and end of the list are changed when using negative strides, just mentions it. – SergeyA Sep 20 '19 at 19:01
  • @SergeyA [This answer](https://stackoverflow.com/a/24713353/789671) (for example) goes into a bit more detail. – glibdud Sep 20 '19 at 19:03
  • @glibdud thanks for the link. It's a pity it is not reflected in official documentation (at least, I was not able to find it). – SergeyA Sep 20 '19 at 19:06
  • @SergeyA It behaves exactly like `range` does (`range(end, start, negative_step)`) – DeepSpace Sep 20 '19 at 19:36
  • @DeepSpace I do not immediately see where it explains how negative step forces reverse iteration with default arguments. – SergeyA Sep 20 '19 at 19:39
  • @glibdud You are actually right, the second answer does go more into the details of this behavior(when one or more of the indexes is `None`) . @SergeyA it is written in the part, where the full notation (`my_list[-9:None:None]`) is talked about. Just after the **Explanation** header – Alex.Kh Sep 20 '19 at 19:42

0 Answers0