0

I want to be able to define a function as having an argument of an unspecified array. For example,

import numpy as np
def cols(np.array([]): 
    return len(np.array([])

Say that:

x=np.array([[1,2,3],[4,5,6]])

Then I want cols(x) to give output 3.

Note, the input must be a np.array, so please no workaround to that!

3
  • 2
    def cols(arr)? and why would you think this array gives you length of 3? Commented May 12, 2022 at 12:28
  • @Guy yupp this solved it Commented May 12, 2022 at 12:34
  • In you example, len(x) is equal to 2. If you want to get the size of the nested arrays (in other words the number of columns of x), you can use x.shape[1]. Commented May 12, 2022 at 12:35

1 Answer 1

1

You don't have to specify what is your argument in python

import numpy as np

def cols(arr):
    return arr.shape[1]

number_of_cols = cols(np.array([[1, 2, 3], [4, 5, 6]]))
print(number_of_cols) # will print 3

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I'm quite new and this fixed it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.