Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice to index or end, if end is lesser then index (python)

Tags:

python

slice

I would like to get slice for some np.ndarray object foo:

bar = foo[:end]

But sometimes end can be greater than len(foo). Then I would like to get bar = foo. I can reach this, if I write bar = foo[:min(end, len(foo)]. But it seems not pythonic. Is there simpler way to do this?

like image 420
nik Avatar asked Dec 22 '25 00:12

nik


1 Answers

You actually don't need any special logic to handle slicing out of range. By default if end is too large, the slice will include the end of the array.

>>> a = np.array([1,2,3])
>>> a
array([1, 2, 3])
>>> a = a[:10]
>>> a
array([1, 2, 3])
like image 188
Cory Kramer Avatar answered Dec 24 '25 15:12

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!