Python whole reverse list specifying index

None can be explicitly provided to indicate "to end" (for negative step, the "end" is the beginning of the sequence):

lst[:ind - 1 if ind else None:-1]

While you did say you were avoiding the two step approach, it's frankly simpler to do it that way; unless you expect the slice to be huge, the simplicity gain is worth whatever trivial performance loss you might suffer:

lst[ind:][::-1]

For the record, on trivial microbenchmarks, assuming each ind value is equally common, the one-step approach is faster, but the difference is fairly small unless your list is huge. For example, for your four element list using ipython for microbenchmarking:

>>> lst = [1, 2, 3, 4]
>>> %%timeit -r5 inds = range(len(lst))
... for ind in inds:
...     lst[:ind-1 if ind else None:-1]
...
1000000 loops, best of 5: 791 ns per loop

>>> %%timeit -r5 inds = range(len(lst))
... for ind in inds:
...     lst[ind:][::-1]
...
1000000 loops, best of 5: 1.1 µs per loop

That's slower, but the cost is only about 300 ns. Even when lst is len 4000, the difference is 18 vs 35.5 ms per loop; granted, that's nearly doubling the time, but if it's not performance critical (or the lists are usually smaller), I'd call that acceptable, since it eases maintainer burden to read "slice from ind to end, then reverse it" rather than the more complicated structure of the one step slice.

Tags:

Python

List