Test if a variable is a list or tuple

interstar picture interstar · Feb 2, 2010 · Viewed 330.1k times · Source

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://www.canonical.org/~kragen/isinstance/

Update: the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / data-structure of lists of lists of lists of strings etc. which I'm exploring with a recursive algorithm and I need to know when I've hit the "leaf" nodes.

Answer

wall-e picture wall-e · Nov 23, 2011
if type(x) is list:
    print 'a list'
elif type(x) is tuple:
    print 'a tuple'
else:
    print 'neither a tuple or a list'