In python, what\'s the best way to test if a variable contains a list or a tuple? (ie. a collection)
Is isinstance()
as evil as suggested here? http://w
In principle, I agree with Ignacio, above, but you can also use type to check if something is a tuple or a list.
>>> a = (1,)
>>> type(a)
(type 'tuple')
>>> a = [1]
>>> type(a)
(type 'list')
if type(x) is list:
print 'a list'
elif type(x) is tuple:
print 'a tuple'
else:
print 'neither a tuple or a list'
Has to be more complex test if you really want to handle just about anything as function argument.
type(a) != type('') and hasattr(a, "__iter__")
Although, usually it's enough to just spell out that a function expects iterable and then check only type(a) != type('')
.
Also it may happen that for a string you have a simple processing path or you are going to be nice and do a split etc., so you don't want to yell at strings and if someone sends you something weird, just let him have an exception.
On Python 2.8 type(list) is list
returns false
I would suggest comparing the type in this horrible way:
if type(a) == type([]) :
print "variable a is a list"
(well at least on my system, using anaconda on Mac OS X Yosemite)
Not the most elegant, but I do (for Python 3):
if hasattr(instance, '__iter__') and not isinstance(instance, (str, bytes)):
...
This allows other iterables (like Django querysets) but excludes strings and bytestrings. I typically use this in functions that accept either a single object ID or a list of object IDs. Sometimes the object IDs can be strings and I don't want to iterate over those character by character. :)
Python uses "Duck typing", i.e. if a variable kwaks like a duck, it must be a duck. In your case, you probably want it to be iterable, or you want to access the item at a certain index. You should just do this: i.e. use the object in for var:
or var[idx]
inside a try
block, and if you get an exception it wasn't a duck...