Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid inconsistent s[i:-j] slicing behaviour when j is sometimes 0?

I am creating a number of slices [-WINDOW-i:-i] of a list, where i ranges between 32 and 0:

vals = []

for i in range(32, -1, -1):
    vals.append(other_list[-WINDOW-i:-i])

When i == 0, this returns a slice of length 0:

other_list[-WINDOW-0:0]

I don't want to have to do this to solve it:

vals = []

for i in range(32, -1, -1):
    if i == 0:
       vals.append(other_list[-WINDOW:])
    else:
       vals.append(other_list[-WINDOW-i:-i])

… because if I have many lists to append to vals, it gets messy.

Is there a clean way to do this?

like image 231
shell Avatar asked Mar 12 '17 21:03

shell


People also ask

Are slices inclusive?

Python is a zero-indexed language (things start counting from zero), and is also left inclusive, right exclusive you are when specifying a range of values. This applies to objects like lists and Series , where the first element has a position (index) of 0.

What is the default step size of slicing?

Specify Step of the Slicing You can specify the step of the slicing using step parameter. The step parameter is optional and by default 1.

How does Python slicing work?

Python slice() FunctionThe slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.


1 Answers

One workaround for this quirk in Python slicing is to take advantage of these facts:

  1. false_ish_value or other_value always evaluates to other_value
  2. 0 is the only integer that is false-ish in a boolean context
  3. s[n:None] is equivalent to s[n:]

With those in mind, you can write your slice as:

other_list[-WINDOW-i:(-i or None)]

… and the slice will be interpreted as [-WINDOW-i:None] (which is the same as [-WINDOW-i:]) only when i (and therefore -i) is 0.

like image 69
Zero Piraeus Avatar answered Oct 11 '22 12:10

Zero Piraeus