-1

Let's say we have

import numpy as np
z = np.array([1, 2, 3, 4, 5, 6])

In some cases, I'd like to define a "numpy range" as a global constant, i.e. instead of doing

print(z[2:4])

with hard-coded values 2 and 4 everywhere in my code, I'd prefer (pseudo-code):

MY_CONSTANT_RANGE = 2:4  # defined once

print(z[MY_CONSTANT_RANGE])

Is there a way to do this? With a numpy range object maybe?

PS: of course we could do

RANGE_MIN, RANGE_MAX = 2, 4
z[RANGE_MIN:RANGE_MAX]

but I am curious if there is a way to define a range constant.

Basj
  • 41,386
  • 99
  • 383
  • 673

2 Answers2

4

Use slice object:

MY_CONSTANT_RANGE = slice(2, 4)

In [205]: z[MY_CONSTANT_RANGE]
Out[205]: array([3, 4])
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

Another way could be to do

MY_CONSTANT_RANGE = np.s_[2:4]
print(z[MY_CONSTANT_RANGE])
shahkalpesh
  • 33,172
  • 3
  • 63
  • 88