Negative Python Null Slicer

I often have to work with the last n elements in the sequence, where n can be 0. The problem is that trying to cut off [-n:]will not work in the case n == 0, so the special case code is inconveniently required. for instance

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 a way to get this behavior without requiring a special inconvenient case? The code would be much simpler if I hadn't had to check 0 all the time.

+5
source share
5 answers

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

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

Just use coalescing behavior or.

>>> print 4 or None
4
>>> print -3 or None
-3
>>> print -0 or None
None
+7
source

, , .

def last(alist, n):
    if n:
        return alist[:-n]
    return alist

newstack = last(self.stack, len(b)) + a

, EOL :

def last(alist, n):
    return alist[:-n] if n else alist[:]
+1

This is likely to be terribly inefficient due to double reversal, but hopefully there is an idea to reverse the sequence to make indexing easier:

a = [11, 7, 5, 8, 2, 6]

def get_last_n(seq, n):
    back_seq = seq[::-1]
    select = back_seq[:n]
    return select[::-1]

print(get_last_n(a, 3))
print(get_last_n(a, 0))

Return:

[8, 2, 6]
[]
0
source

You can skip the legend there

L[-i if i else len(L):]

I think this version is less clear. You should use a comment next to it.

L[-i or len(L):]
0
source

All Articles