How to know it is a list?

David Bolen db3l at fitlinxx.com
Mon Sep 10 18:20:55 EDT 2001


"Henry" <ht_xu at hotrmail.com> writes:

>   I have a newbie question. How do check if a variable is a list?

Other responders have already shown some methods, but it can also be
helpful to ask in response to this sort of question - "why" you need
to know it?

For example, if you have code that assumes it is going to append a new
element to a list, it'll probably be using the "append" method.  So
you might consider verifying that you have been passed a list before
performing the append.  But if you do that, then if someone tries to
pass you another object (that also happens to implement an append
method) you'll refuse to work when you would actually work just fine.

That's not to say that there aren't cases where identifying a specific
type can be practical, but often doing so is going to interfere with
the polymorphic value of the code you are writing.  So you may want to
at least ask yourself if you really need to know that an object is a
list, or might you instead really want to know if an object behaves
like a list.  The latter test can be made by introspecting for a
particular method, or even just trying an operation in a try/except
block.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list