Isinstance in Python, What does Isinstance () do in Python?

isinstance() is a built-in function in Python that allows you to check if an object is an instance of a specified type. It takes two arguments: the object you want to check, and the type you want to check it against. If the object is an instance of the specified type, isinstance() returns True, otherwise it returns False.

Here’s an example of how to use isinstance():

my_var = "hello"

if isinstance(my_var, str):
    print("my_var is a string")
else:
    print("my_var is not a string")

In this example, the code will print “my_var is a string” because my_var is a string.

isinstance() is a useful function because it can also check if an object is an instance of a subclass of the specified type. For example:

class MyString(str):
    pass

my_var = MyString("hello")

if isinstance(my_var, str):
    print("my_var is a string")
else:
    print("my_var is not a string")

In this case, the code will still print “my_var is a string” because MyString is a subclass of str.

Isinstance Python multiple types (How do you check for multiple types in Python?)

o check if an object is an instance of multiple types in Python, you can pass a tuple of types to the isinstance() function as the second argument. isinstance() will return True if the object is an instance of any of the specified types, and False if it is not. For example:

my_var = "hello"

if isinstance(my_var, (int, str)):
    print("my_var is a string or an integer")
else:
    print("my_var is not a string or an integer")

In this case, the code will print “my_var is a string or an integer” because my_var is a string.

Python isinstance list :- Checking if type == list in python

To check if a variable is a list in Python, you can use the isinstance() function with the list type as the second argument. Here’s an example:

my_var = [1, 2, 3]

if isinstance(my_var, list):
    print("my_var is a list")
else:
    print("my_var is not a list")

In this case, the code will still print “my_var is a list” because MList is a subclass of list.

Leave a Comment