0

First time using StackOverflow, apologies in-case of any issues.


In python,

list[::-1] returns the reversed list

list[0:len(list)+1] returns the complete list

So why list[0:len(list)+1:-1] returns an empty list?


Further, for a list l= [0,1,2,3,4,5], if I want like [4,3,2]:

Trying l[2:5:-1], returns an empty list. But l[2:5][::-1] works.


Can anyone explain why this is happening? Or what is python actually doing when we slice a list, with a value for step?

Thanks in advance :)

U13-Forward
  • 69,221
  • 14
  • 89
  • 114

1 Answers1

1

some_list[start:stop:step] means give me elements starting at start and incrementing by step until you hit stop.

Well, if you start at 0 and increment by -1, you never actually reach the stop.

cadolphs
  • 9,014
  • 1
  • 24
  • 41
  • Thank you for answering, it cleared things up but had a follow-up question. For ```l= [0,1,2,3,4,5,6,7,8,9,10]```, why does ```l[0:-6:-1]``` return an empty string? Since it does reach the stop value – Utkarsh Pant Nov 09 '21 at 13:35