Is there a short way in Python to check if an object is list-like (i.e. a `Sequence` but not a `str`)?

Viewed 51

The shortest (readable) form I've got is:

isinstance(obj, collections.abc.Sequence) and not isinstance(obj, str)

I was looking through the docs for collections.abc and was surprised to find that there isn't already a unique type to represent that.

Then I learned that isinstance accepts a tuple of types to check against, but sadly, it doesn't also accept a tuple of exceptions.

Finally, I learned about the Union type, which has a nice syntax sugar where you can just bitwise-or types together, like so for instance: int | float. So naturally, I tried doing collections.abc.Sequence & ~str, which didn't work.

1 Answers

A characteristic of the str type is that it is a sequence, but immutable. So most types which you want to cover are mutable sequences.

There is the MutableSequence abstract base class which represents this behavior.

Related