Test for structure

Terry Hancock hancock at anansispaceworks.com
Sat Feb 19 01:05:49 EST 2005


On Wednesday 16 February 2005 09:08 am, alex wrote:
> how can I check if a variable is a structure (i.e. a list)? For my
> special problem the variable is either a character string OR a list of
> character strings line ['word1', 'word2',...]
> 
> So how can I test if a variable 'a' is either a single character string
> or a list?

The literally correct but actually wrong answer is:

if type(a) == type([]):
    print "'a' is a duck"

But you probably shouldn't do that. You should probably just test to
see if the object is iterable --- does it have an __iter__ method?

Which might look like this:

if hasattr(a, '__iter__'):
    print "'a' quacks like a duck"

That way your function will also work if a happens to be a tuple,
a dictionary, or a user-defined class instance which is happens to
be  iterable.

Being "iterable" means that code like:

for i in a:
   print "i=%s is an element of a" % repr(i)

works.  Which is probably why you wanted to know, right?

Cheers,
Terry

-- 
--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list