Testing for a list

Steve Holden sholden at holdenweb.com
Mon Mar 10 14:20:49 EST 2003


"Antun Karlovac" <antun at antunkarlovac.com> wrote ...
> Is there a way to test if a variable is a list?
>
> i.e.
>
>   a = []
>
> If I have 'a', I need to know whether it is a list or a string.
>

If you are only interested in whether it is a list then probably the easiest
way to test is to write

    if type(a) == list

In 2.2 and beyond the built-in types are each bound to a suitable name
(dict, str, list, etc.).

However, your question begs other, larger questions. Firstly, can you ignore
subclasses of list, other sequence types, etc.? If not, then you may want to
use isinstance(), which can recognize subclasses as well.

Secondly, there are a large number of circumstances in which it really isn't
a good idead to be recognising the type of an object in such a hard-coded
way. Do you really want to know it's a list, or do you simply need to be
able to iterate over it, for example? If the latter, simply trying the
iteration and catching any errors with a try/except might be a more
sensiblke approach.

regards
--
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Register for PyCon now!            http://www.python.org/pycon/reg.html






More information about the Python-list mailing list