nik
nik

Reputation: 355

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

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

Answers (1)

Cory Kramer
Cory Kramer

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

Related Questions