Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 292
Antimony Avatar asked Jul 05 '12 04:07

Antimony


1 Answers

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:]
[]
like image 80
jamylak Avatar answered Sep 28 '22 09:09

jamylak