Search code examples
pythonidiomsslice

Python negative zero slicing


I often find myself having to work with the last n items in a sequence, where n may be 0. The problem is that trying to slice with [-n:] won't work in the case of n == 0, so awkward special case code is required. For example

if len(b): 
    assert(isAssignableSeq(env, self.stack[-len(b):], b))
    newstack = self.stack[:-len(b)] + a
else: #special code required if len=0 since slice[-0:] doesn't do what we want
    newstack = self.stack + a

My question is - is there any way to get this behavior without requiring the awkward special casing? The code would be much simpler if I didn't have to check for 0 all the time.


Solution

  • You can switch it from L[-2:] to L[len(L)-2:]

    >>> L = [1,2,3,4,5]
    >>> L[len(L)-2:]
    [4, 5]
    >>> L[len(L)-0:]
    []