0

How do I print the reverse of a specific selection of a list ?

For example, I have a list,

a = [11,22,33,44,55,66,77,88]

I expect a[1:4:-1] to print [44,33,22], but it gives an empty list.

I have seen Understanding slicing, but I couldn't find an answer.

Mathew S
  • 3
  • 3
  • [This answer on Understanding slicing](https://stackoverflow.com/a/509377/364696) directly addresses how negative strides affect the interpretation of start and stop; it would answer your question by itself. – ShadowRanger Feb 15 '23 at 01:02
  • Note that 99% of the time, trying to mix selection and reversing in the same slice is just confusing as hell, and unless performance *really* counts, it's easier to just do the forward slice and follow with the canonical reversing slice, e.g. in this case `a[1:4][::-1]`. `a[1:4]` gets the elements you want, `[::-1]` produces the reversed version of the selected elements. – ShadowRanger Feb 15 '23 at 01:04

1 Answers1

0

The python slicing syntax, when 3 parameters are provided, is [start:stop:step]

In order to get the value [44, 33, 22], you'd need to write the slice like this: a[3:0:-1]

This works because the slice starts at index 3, which has a value of 44, and the slice stops before index 0, meaning the last included index is 1 (with a value of 22), based on the step value of -1.

David Culbreth
  • 2,610
  • 16
  • 26