python: how to identify if a variable is an array or a scalar
isinstance([0, 10, 20, 30], list)Trueisinstance(50, list)False
To support any type of sequence, check
collections.Sequence instead of
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))
Combining @jamylak and @jpaddison3's answers together, if you need to be robust against numpy arrays as the input and handle them in the same way as lists, you should use
import numpy as npisinstance(P, (list, tuple, np.ndarray))
This is robust against subclasses of list, tuple and numpy arrays.
And if you want to be robust against all other subclasses of sequence as well (not just list and tuple), use
import collectionsimport numpy as npisinstance(P, (collections.Sequence, np.ndarray))
Why should you do things this way with
isinstance and not compare
type(P) with a target value? Here is an example, where we make and study the behaviour of
NewList, a trivial subclass of list.
class NewList(list): isThisAList = '???'x = NewList([0,1]) y = list([0,1])print x[0, 1]print y[0, 1] x==yTruetype(x)<class '__main__.NewList'>type(x) is listFalsetype(y) is listTruetype(x).__name__'NewList'isinstance(x, list)True
y comparing as equal, handling them by
type would result in different behaviour. However, since
x is an instance of a subclass of
isinstance(x,list) gives the desired behaviour and treats
y in the same manner.