How to get the type of an object?

Dennis Benzinger Dennis.Benzinger at gmx.net
Wed Dec 21 18:34:48 CET 2005


Licheng Fang schrieb:
> I wrote a function with a list as its parameter. And the function has
> to perform different operations based on the datatypes of the elements.
> How can I decide whether an object is, say, a list or a string?
> 
> Thanks.
> 

To check if an object is of a particular type use isinstance(), to get 
the type of an object use type(). You can read more about this two 
function in the built-in functions documentation 
<http://www.python.org/doc/2.4.2/lib/built-in-funcs.html>. The types 
module <http://www.python.org/doc/2.4.2/lib/module-types.html> may also 
help you.

Small example:

a_list = [1, "two", [3], (4,), {5: 5}]


for item in a_list:
     if isinstance(item, list):
         print "It's a list"
     else:
         print type(item)


Bye,
Dennis



More information about the Python-list mailing list