How to determine a Python variable's type?

 

In Python, you can determine the type of a variable using the type() function or the isinstance() function. Here are examples of both methods:

Using the type() function:

The type() function returns the type of an object. Here's an example:

python
# Define variables of different types integer_variable = 42 string_variable = "Hello, world!" list_variable = [1, 2, 3] dict_variable = {"name": "John", "age": 30} # Determine the types of variables print(type(integer_variable)) # <class 'int'> print(type(string_variable)) # <class 'str'> print(type(list_variable)) # <class 'list'> print(type(dict_variable)) # <class 'dict'>

In this example, we use type() to determine the types of different variables.

Using the isinstance() function:

The isinstance() function is used to check if an object is an instance of a particular class or type. It returns a boolean value (True or False). Here's an example:

python
# Define variables of different types integer_variable = 42 string_variable = "Hello, world!" list_variable = [1, 2, 3] dict_variable = {"name": "John", "age": 30} # Check if variables are of specific types print(isinstance(integer_variable, int)) # True print(isinstance(string_variable, str)) # True print(isinstance(list_variable, list)) # True print(isinstance(dict_variable, dict)) # True # You can also use isinstance() for multiple types print(isinstance(integer_variable, (int, float))) # True, since int is a subclass of float

In this example, we use isinstance() to check if variables belong to specific types or classes. Note that you can also pass a tuple of types to check against multiple types simultaneously.

These methods allow you to determine the type of a Python variable, which can be useful for making decisions or performing type-specific operations in your code.

Comments