How do I test if an object is a sequence?

Skip Montanaro skip at pobox.com
Mon Dec 22 09:39:39 EST 2003


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

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

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

    Max> So it will need to be expanded to:

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

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

    Max> There must be a better way?

Not really.  You're better off testing for whatever operations you want to
perform.  You run the risk of overlapping with mapping objects, but that's
life.

Skip






More information about the Python-list mailing list