Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if object is of str or list or dict or int?

Tags:

python

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)
like image 325
d-coder Avatar asked Sep 26 '14 07:09

d-coder


People also ask

How do I determine the type of an object in Python?

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.

How do you check if a value is in a string or list in Python?

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.

How do you check if a class object is in a list Python?

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.

How do you check if a string is in a dict?

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.


2 Answers

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.

like image 142
Aaron Digulla Avatar answered Nov 03 '22 01:11

Aaron Digulla


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)
like image 21
Tushar Avatar answered Nov 03 '22 03:11

Tushar