What value do I use in a slicing range to include the last value in a numpy array?
numpy, python, scipy
Solution
It's a bit of a pain, but since `-0` is the same as `0`, there is no easy solution.
One way to do it would be:
l = list()
for k in [5,4,3,2,1,0]:
l.append(x[:-k or None])
This is because when `k` is 0, `-k or None` is `None`, and `x[:None]` will do what you want. For other values of `k`, `-k or None` will be `-k`.
I am not sure if I like it myself though.
Problem
Imagine some numpy array, e.g. `x = np.linspace(1,10)`. `x[i:j]` gives me a view into `x` for the range `[i,j)`. I love that I can also do `x[i:-k]` which excludes the last `k` elements. However, in order to include the last element I need to do `x[i:]`. My question is this: How do I combine these two notations if I for instance need to loop over `k`. Say that I want to do this: ``` l = list() for k in [5,4,3,2,1]: l.append(x[:-k]) l.append(x[:]) ``` What annoys me is that last line. In this simple example of course it doesn't do much of a difference, but sometimes this becomes much more annoying. What I miss is something more DRY-like. The following snippet course does NOT yield the desired result, but represents the style of code I seek: ``` l = list() for k in [5,4,3,2,1,0]: l.append(x[:-k]) ```