Python negative zero slicing

Question:

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.

Asked By: Antimony

||

Answers:

Just use or‘s coalescing behavior.

>>> print 4 or None
4
>>> print -3 or None
-3
>>> print -0 or None
None

Explanation (from comments): In your case it would look like this
self.stack[:(-len(b) or None)] reduces to self.stack[:None] if len(b) is 0, which in turn reduces to self.stack[:]

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:]
[]
Answered By: jamylak

When you find yourself using a construct more than once, turn it into a function.

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

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

An even simpler version as suggested by EOL in the comments:

def last(alist, n):
    return alist[:-n] if n else alist[:]
Answered By: Mark Ransom

This is likely to be horribly inefficient, thanks to the double-reversing, but hopefully there’s something to the idea of reversing the sequence to make the 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))

Returns:

[8, 2, 6]
[]
Answered By: Marius

You can slip a conditional in there

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

I think this version is less clear. You should use a comment along side it

L[-i or len(L):]
Answered By: John La Rooy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.