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?
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With