1
l=[1,2,3,4,5,6,7,8,9,10]
print l[7:-9:-1]

the output for above code is

[8, 7, 6, 5, 4, 3]

How list slicing works here?

user5319825
  • 491
  • 1
  • 6
  • 16

1 Answers1

1

The slice syntax is

mylist[ <index_of_first_element(included)> : <index_of_endpoint_element(excluded)> : <stepsize>]

Negative indices work their way backwords. In this case, -9 is the 9th element backwards from the end (i.e. "2")

Python is zero-indexed, so index 7 here has value "8"

So you're telling python to get the element with index 7 (i.e. the 8th element, since python is zero-indexed) which here is "8", then go backwards one index value at a time (because stepsize is "-1") until you reach the "endpoint" element with index -9 (which here is "2"), and without including that endpoint (because this is how slicing is defined).

David Makogon
  • 69,407
  • 21
  • 141
  • 189
Tasos Papastylianou
  • 21,371
  • 2
  • 28
  • 57