Python type() Function Tutorial

In this section, we will learn what the type() function is and how to use it in Python.

Python Check Type via type() Function

The `type()` function is used to get the type of an object. For example, if there’s a variable that is pointing to an integer value, then invoking this function on such a variable will return an int class to mention that the value of the target variable is of type int.

Python type() Function Syntax

type(obj)

The method takes one argument and that is the object (value or a variable that is pointing to a value) that we want to take its type.

Note: there’s another variant of this function as well, but the one you saw here is the most used one.

Example: using type() function in Python

print(type("stri"))

print(type(10))

print (type(32.22))

Output:

<class 'str'>

<class 'int'>

<class 'float'>

Note: the use of `print()` function is to send the result of the call to the `type()` function to the output stream. You’ll learn more about functions in the Python function section.

Example: getting type of a variable via Python type() function

print(type((1,2,3,4,5)))

print (type([1,2,3,4,5]))

Output:

<class 'tuple'>

<class 'list'>

Example: get type in Python

The example below is for those who already familiar with `is` operator and `if` statement. But if you’re not familiar with these concepts yet, don’t worry they are covered in later sections. So feel free to skip this example for now.

result1 =type((1,2,3,4,5))
result2 = type([1,2,3,4,5])
if (result1 is tuple):
    print("The type is tuple")

if (result2 is list):
    print("The type is list")

Output:

The type is tuple

The type is list
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies