How to detect list versus string

Donn Cave donn at
Sat Jun 12 17:21:11 CEST 2004

Quoth Jonathon McKitrick <jcm at>:

| I have a method that builds a dynamic combo box.  Before I do that, I set a
| class variable to the new list of items.
| def make_new_cat_box(self, cats):
| 	self.cat_list = cats
| Sounds simple.  But sometimes, my combo box will only have one choice
| available.  When I call this method with a list of one string, the string is
| split up, and my combo box now has a separate item for each letter in the
| string.  What I obviously want to do is detect when the object coming in is
| a list or a string.  type() isn't as useful as I had hoped, and len() will
| give me the length of the string, so I cannot tell if it is a string or a
| list of more that one item.

Well, there are a variety of approaches.  Some programmers like to try
to discriminate on the basis of functional distinctions, so for example
they'll try to add two quantities together to see if their types are
compatible in that respect.  Since you apparently don't get tuples, only
lists, you could test for hasattr(cats, 'append').  Etc.

But what's going on there, really?  `When I call this method with a list
of one string ...?'  Like this, a.make_new_cat_box([v])?  Why would that
put you in this spot?

It sounds like you're really calling this method with just a string, not
a list of one string.  In which case, if you can avoid that, please do,
put the string in a list and consider the problem solved!

	Donn Cave, donn at

More information about the Python-list mailing list