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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…