Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What value do I use in a slicing range to include the last value in a numpy array?

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])
like image 330
Julius Avatar asked Mar 26 '13 00:03

Julius


People also ask

How do you slice the last element in Python?

Method #1 : Using None During list slicing, giving the desired first index K and specifying 'None' as the second argument in slicing works internally as slicing all the elements from K in list till end including it.

How do I select the last row of a NumPy array?

If you to select the last element of the array, you can use index [11] , as you know that indexing in Python begins with [0] .

How do you slice a value in a list in Python?

You can generate a slice object using the built-in function slice() . If you want to repeatedly select the items at the same position, you only need to generate the slice object once. slice(start, stop, step) is equivalent to start:stop:step . If two arguments are specified, step is set to None .

When slicing a list What does it mean if there isn't a value after the first colon?

If there isn't a value after the first colon, it means to go all the way to the end of the list. This saves us time so that we don't have to manually specify len(a) as the ending index. Okay. And that -1 I snuck in at the end?


1 Answers

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.

like image 89
Alok Singhal Avatar answered Oct 14 '22 21:10

Alok Singhal