How to get the type of an object?

L

Licheng Fang

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.
 
S

smichr

You can use the type() function:

###True
###

You can do the same with list, too. So you could write,

if type(x)==list:
#do list action

/c
 
D

Dennis Benzinger

Licheng said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top