Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: how to identify if a variable is an array or a scalar

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?

thanks

like image 359
otmezger Avatar asked May 29 '13 06:05

otmezger


People also ask

How do you check if a variable is a scalar or an array in Python?

To check if an element is scalar or not in Python, use the numpy isscalar() method. The isscalar() function returns True if the type of num is a scalar type.

How do you check the type of a variable in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

How do you know if a value is scalar?

The is_scalar() function checks whether a variable is a scalar or not. This function returns true (1) if the variable is a scalar, otherwise it returns false/nothing. Integers, floats, strings, or boolean can be scalar variables. Arrays, objects, and resources are not.

What is the difference between scalar and array variables?

Briefly, a scalar is one variable - for example an integer. It can take different values at different times, but at any one time it only has one single value. An array is a set of variables - in most languages these all have to be of the same type.


1 Answers

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

To support any type of sequence, check collections.Sequence instead of list.

note: isinstance also supports a tuple of classes, check type(x) in (..., ...) should be avoided and is unnecessary.

You may also wanna check not isinstance(x, (str, unicode))

like image 112
jamylak Avatar answered Sep 20 '22 22:09

jamylak