Reputation: 4155
What is the best way to find out the object type of each item in a list?
I have been using the below but it is very cumbersome and requires that one knows of the object type in order to be able to test for it.
for form in form_list:
if type(form) is list:
print 'it is a list'
else:
print 'it is not a list'
if type(form) is dict:
print 'it is a dict'
else:
print 'it is not a dict'
if type(form) is tuple:
print 'it is a tuple'
else:
print 'it is not a tuple'
if type(form) is str:
print 'it is a string'
else:
print 'it is not a string'
if type(form) is int:
print 'it is an int'
else:
print 'it is not an int'
Upvotes: 1
Views: 414
Reputation: 6617
In Python 2.7:
form_list = ['blah', 12, [], {}, 'yeah!']
print map(type, form_list)
[str, int, list, dict, str]
In Python 3.4:
form_list = ['blah', 12, [], {}, 'yeah!']
print(list(map(type, form_list)))
[<class 'str'>, <class 'int'>, <class 'list'>, <class 'dict'>, <class 'str'>]
Upvotes: 3
Reputation: 1112
Knowing type in python is oftentimes not the desired way to go. Read up on the topic duck-typing
if you're new to this.
If you still want to go down this path, do:
objtype = type(form)
if objtype is list:
#do stuff
elif objtype is str:
#do other stuff
else:
#can't handle this
and so on
Upvotes: 1