Wesley Bowman
Wesley Bowman

Reputation: 1396

Simply way to set default index of an array to be all unless specified

Let's say I have a numpy array (the following will be a trivial example of what I am trying to achieve)

test = np.array([[0,1,2][3,4,5]])

and I want the user to be able to specify a index that they want to view

ind = 4

but I want this to be in a function

def view(array, index):
    print array[index]

If the user doesn't input an index, I want it to print the entire array.

test[:]

Is there a way to do this simply? I know you could do it with an if statement, but when I need to do this for 10 different arrays, the code become clunky when I figured there had to be a simpler way to do it.

So right now my method would consist of

def view(array, index=False):
    if index:
         print array[index]
    else:
         print array[:]

I am asking if there is a more efficient or more pythonic way of achieving this.

Upvotes: 0

Views: 58

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122065

You can make the default value for the index parameter a slice object using the built-in slice function:

>>> def view(array, index=slice(None)):
    print array[index]


>>> view(test)
[[0 1 2]
 [3 4 5]]
>>> view(test, 1)
[3 4 5]

Upvotes: 3

Related Questions