Full Python Index Index Index

I have a list in which I want to get the last few elements in reverse order:

lst = [1,2,3,4] 

I can cancel the list with lst[::-1] and return the whole list. But I want the list to be flipped only to a specific index. I can specify an index:

 ind = 1 lst[:ind-1:-1] 

and get:

 [4, 3, 2] 

which is the source list up to the specified index, in reverse order. This works for any index> 0. But if ind is 0 (this means the whole list should be returned in reverse order), this causes a problem:

 ind = 0 lst[:ind-1:-1] 

returns:

 [] 

because my final place is the same as my start (-1). My expected / desired result would be [4, 3, 2, 1]

I know that a simple solution would be to simply put an if statement to catch the case where ind is 0, or do it in two steps (the index is then the reverse), but it seems like this should be done using the indexing system in Python. I am wrong?

+8
python list
source share
2 answers

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

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

While you said you were avoiding a two-step approach, it was, frankly, easier to do so; if you don't expect the chunk to be huge, simplicity will be worth any trivial performance loss that you might suffer:

 lst[ind:][::-1] 

For recording on trivial microobjects, assuming each ind value is equally common, the one-step approach is faster, but the difference is pretty small, if only your list is huge. For example, for your four list items using ipython for microdetection:

 >>> 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 

This is slower, but the cost is only about 300 ns. Even when lst is len 4000, the difference is 18 versus 35.5 ms per cycle; which almost doubles the time, but if it is not performance critical (or lists are usually smaller), I would call it acceptable, since it eases the load on the media to read "a fragment from ind to the end, and then vice versa", and no more complex single-stage cut structure.

+5
source share

A simple technique is to use

ind = 1

lst [: ind: -1] = This will flip the list of values ​​from the mentioned index.

0
source share

All Articles