Reputation: 13963
I have a list of lists and then I'm extracting the last element from the list. Now, how to know whether it's of type str
or list
or dict
or int
?
list2 = response_list[0][-1]
print list2,type(list2)
print "not executing"
print list2
I have failed to match if that element is list
or str
by the following code:
list2 = response_list[0][-1]
if type(list2) == str() :
print list2,type(list2)
elif type(list2) == list() :
print list2,type(list2)
Upvotes: 12
Views: 17441
Reputation: 1
Try the below using type function, pretty clean yeah?
dict, str, tuple, int
if type(d) is dict:
True
Upvotes: 0
Reputation: 9647
You can rearrange your code like this,
list2 = response_list[0][-1]
if type(list2) == str:
print list2,type(list2)
elif type(list2) == list:
print list2,type(list2)
Upvotes: 0
Reputation: 15923
Actually the type function works as
>>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>
For comparision you can use isinstance()
function which returns True/False
list2 = response_list[0][-1]
if isinstance(list2,str):
print list2,type(list2)
elif isinstance(list2,list):
print list2,type(list2)
Upvotes: 1
Reputation: 328614
Since Python 2.2, you should use this code:
if isinstance(list2, (str, list, dict)):
isinstance()
takes a tuple as second argument and returns true
if the type is in the tuple.
Upvotes: 26