Python: check if an object is a sequence

iter(x) will raise a TypeError if x cannot be iterated on — but that check “accepts” sets and dictionaries, though it “rejects” other non-sequences such as None and numbers.

On the other hands, strings (which most applications want to consider “single items” rather than sequences) are in fact sequences (so, any test, unless specialcased for strings, is going to confirm that they are). So, such simple checks are often not sufficient.

In Python 2.6 and better, abstract base classes were introduced, and among other powerful features they offer more good, systematic support for such “category checking”.

>>> import collections
>>> isinstance([], collections.Sequence)
True
>>> isinstance((), collections.Sequence)
True
>>> isinstance(23, collections.Sequence)
False
>>> isinstance('foo', collections.Sequence)
True
>>> isinstance({}, collections.Sequence)
False
>>> isinstance(set(), collections.Sequence)
False

You’ll note strings are still considered “a sequence” (since they are), but at least you get dicts and sets out of the way. If you want to exclude strings from your concept of “being sequences”, you could use collections.MutableSequence (but that also excludes tuples, which, like strings, are sequences, but are not mutable), or do it explicitly:

import collections

def issequenceforme(obj):
    if isinstance(obj, basestring):
        return False
    return isinstance(obj, collections.Sequence)

Season to taste, and serve hot!-)

PS: For Python 3, use str instead of basestring, and for Python 3.3+: Abstract Base Classes like Sequence have moved to collections.abc.

Leave a Comment