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.
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:]
[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With