Sridhar Ratnakumar Sridhar Ratnakumar - 1 month ago 11
Python Question

Python: check if an object is a list or tuple (but not string)

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

I think

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.