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)
Syntax of the Python type() functionThe type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object. __class__ instance variable.
Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list.
Use the any() function to check if an object exists in a list of objects. The any() function will return True if the object exists in the list, otherwise False is returned.
Use dict.values() to get the values of a dictionary. Use the expression value in dictionary_values to return True if the value is in the dictionary and False if otherwise.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With