I need to slice a list using negative dynamic indexes ([:-index]). This was easy until I realized that if the value of my dynamic index was 0, no items were returned, instea
Another potential solution for fun.
>>> arr = [1, 2, 3]
>>> index = 0
>>> arr[:-index or None]
[1, 2, 3]
>>> index = 1
>>> arr[:-index or None]
[1, 2]
For higher performance on immutable sequence types like strings, you can avoid slicing the sequence entirely in the case that index is 0 by checking the value of index before the slice operation.
Here's three functions to test in terms of performance:
def shashank1(seq, index):
return seq[:-index or None]
def shashank2(seq, index):
return index and seq[:-index] or seq
def shashank3(seq, index):
return seq[:-index] if index else seq
The latter two should be much faster in the case where index is 0, but may be slower (or faster) in other cases.
Updated benchmark code: http://repl.it/oA5
Note: The results depend quite a bit on the Python implementation.