Reputation: 355
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?
Upvotes: 3
Views: 1501
Reputation: 117926
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])
Upvotes: 5