How do I test if an object is a sequence?

Max M maxm at mxm.dk
Mon Dec 22 09:11:55 EST 2003


Is there a common idiom for testing if an object is a sequence?

Both list, tuple and non-standard objects etc. I have Googled, but 
didn't find a usable answer.


There are a few direct approaches:


def is_sequence(unknown):
     return type(unknown) = type([]) or type(unknown) = type(())

Which is basically the old-school version of:

from types import TupleType, ListType
def is_sequence(unknown):
     return isinstance(unknown, (TupleType, ListType))


But they only check for built in objects.

Then there is the approach of testing for a method that they all share. 
The only one that springs to mind is the slice operation.

def is_sequence(object)
     try:
         test = object[0:0]
     except:
         return False
     else:
         return True


But it has the disadvantage that string also are sequences. But not 
exactly the kind I am interrested in.

So it will need to be expanded to:

from types import StringTypes
def is_sequence(unknown):
     if isinstance(unknown, StringTypes):
         return False
     try:
         test = object[0:0]
         return True
     except:
         return False


But that looks kind of ugly for a "simple" type check.

There must be a better way?


regards Max M





More information about the Python-list mailing list