Python’s type() function – Tutorial with Examples

In Python, the type() function is used to determine the type of an object. It takes an object as an argument and returns the type of the object. This function is a useful tool for debugging and testing, as well as for understanding the structure of objects in Python.

Example usage of type()

Here’s a simple example of using the type() function in Python:

x = 10
print(type(x)) # Output: <class 'int'>

y = "Hello, World!"
print(type(y)) # Output: <class 'str'>

z = [1, 2, 3, 4, 5]
print(type(z)) # Output: <class 'list'>

As you can see, the type() function returns the type of the object that it takes as an argument. In this case, the type of the integer x is int, the type of the string y is str, and the type of the list z is list.

Built-in Types in Python

There are several built-in types in Python, including:

  • int (integers, such as -1, 0, 1, 2, etc.)
  • float (floating point numbers, such as 3.14, 2.718, etc.)
  • str (strings, such as “Hello, World!” or “foo”)
  • list (lists, such as [1, 2, 3, 4, 5])
  • tuple (tuples, such as (1, 2, 3, 4, 5))
  • dict (dictionaries, such as {‘name’: ‘John’, ‘age’: 30})
  • set (sets, such as {1, 2, 3, 4, 5})
  • bool (boolean values, either True or False)

These built-in types are used to represent the most common types of objects in Python, but there are many more types available in the standard library and in third-party libraries.

Creating Custom Types in Python

In addition to the built-in types, you can also create your own custom types in Python. Custom types are created using classes, which allow you to define the structure and behavior of objects in Python. Here’s a simple example of a custom type in Python:

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

my_car = Car("Toyota", "Camry", 2020)
print(type(my_car)) # Output: <class '__main__.Car'>

In this example, we define a custom type Car using a class. The class has a constructor method (__init__) that takes three arguments (make, model, and year) and sets them as instance variables. We then create an instance of the Car type and use the type() function to determine its type, which returns <class ‘main.Car’>. This indicates that the type of my_car is the Car type defined in the main module (main).

Conclusion

The type() function in Python is a useful tool for determining the type of an object. It returns the type of the object that it takes as an argument, and can be used with built-in types or custom types created using classes. Understanding the type of an object is essential for writing effective and efficient Python code, and the type() function provides a simple and straightforward way to do so.

Leave a Reply

Your email address will not be published. Required fields are marked *