How to check if an object is a list or tuple (but not string)?

Sridhar Ratnakumar picture Sridhar Ratnakumar · Dec 2, 2009 · Viewed 541.8k times · Source

This is what I normally do in order to ascertain that the input is a list/tuple - but not a str. Because many times I stumbled upon bugs where a function passes a str object by mistake, and the target function does for x in lst assuming that lst is actually a list or tuple.

assert isinstance(lst, (list, tuple))

My question is: is there a better way of achieving this?

Answer

Nick Craig-Wood picture Nick Craig-Wood · Dec 2, 2009

In python 2 only (not python 3):

assert not isinstance(lst, basestring)

Is actually what you want, otherwise you'll miss out on a lot of things which act like lists, but aren't subclasses of list or tuple.