What Is The Best Way To Check If A Variable Is A List?
Solution 1:
These all express different things, so really it depends on exactly what you wish to achieve:
isinstance(x, list)
check if the type ofx
is eitherlist
or haslist
as a parent class (lets ignore ABCs for simplicity etc);type(x) is list
checks if the type ofx
is preciselylist
;type(x) == list
checks for equality of types, which is not the same as being identical types as the metaclass could conceivably override__eq__
So in order they express the following:
isinstance(x, list)
: isx
like alist
type(x) is list
: isx
precisely alist
and not a sub classtype(x) == list
: isx
a list, or some other type using metaclass magic to masquerade as alist
.
Solution 2:
Do you need to know if it's a list, or just if it's iterable (if you can use it in a for loop, for example)? Generally the "Pythonic way" is to just go ahead and do it in a try-except, because many things can be iterable: strings, lists, sets, deques, custom types, etc. (All it takes is an __iter__
or __getitem__
method)
If you REALLY need to know what type it is, isinstance() is typically the way to go since it will also cover subclasses.
As far as using type() == something
is concerned, int
, float
, list
, etc are all types: type(1) == int
is True
.
My typical approach, where I might have a string, a list (or tuple, etc.) of strings, or an int or other object which can be converted to a string, would be this (for Python 2 - Py3 no longer has basestring
so you'll need to check for str
and/or bytes
), assuming foo
is your variable:
ifisinstance(foo, basestring):
foo = (foo,) # turn it into an iterable (tuple)# or, doStuff(foo) followed by a return or breaktry:
for x in foo:
doStuff(str(x)) # do something with each elementexcept TypeError: # TypeError: 'some' object is not iterable
doStuff(str(foo))
Solution 3:
Usually we prefer, isinstance(a, list)
because it allows a to be either a list or list subclass.
For better speed, an exact check can to an identity test, type(a) is list
. This is a bit faster than using ==
.
That said, the norm in Python is to avoid type checks altogether and instead do "duck typing". You call list methods on a and if they succeed, then we deem a to be sufficiently list like.
Post a Comment for "What Is The Best Way To Check If A Variable Is A List?"