Antimony
Antimony

Reputation: 39451

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.

Upvotes: 19

Views: 3676

Answers (5)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799110

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[:]

Upvotes: 24

John La Rooy
John La Rooy

Reputation: 304355

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):]

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308402

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[:]

Upvotes: 2

Marius
Marius

Reputation: 60160

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]
[]

Upvotes: 0

jamylak
jamylak

Reputation: 133634

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:]
[]

Upvotes: 22

Related Questions