Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (47.6k points)

I have a function that takes the argument NBins. I want to make a call to this function with a scalar 50 or an array [0, 10, 20, 30]. How can I identify within the function, what the length of NBins is? or said differently, if it is a scalar or a vector?

I tried this:

>>> N=[2,3,5]

>>> P = 5

>>> len(N)

3

>>> len(P)

Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'int' has no len()

As you see, I can't apply len to P, since it's not an array... Is there something like isarray or isscalar in python?

2 Answers

0 votes
by (106k points)
edited by

To identify if a variable is an array or a scalar you can use isinstance method below is the code for the same:-

>>> isinstance([0, 10, 20, 30], list)

True

>>> isinstance(50, list)

False

To know more about this you can have a look at the following video:-

For more information, kindly refer to our Python course.

0 votes
by (1.9k points)

Here we can use the np.isscalar method in order to verify the value of the variable NBins is whether it is a scalar or an array.

The code for implementation is given below which will take into consideration the following:

1. Determine whether NBins is a scalar or an array.

2. Print the length of the array in that case.

import numpy as np

def input_bins(NBins):

   if np.isscalar(NBins):

      print(“NBins is a scalar, NBins”). 

   else:

      try:

         length = len(NBins).

         print(“NBins is an array with length:”, length)

      except TypeError: 

         print(“NBins does not comprise of scalar or array like objects”).

input_bins(50)

input_bins([0, 10, 20, 30])

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
asked Jul 13, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...