Python: How to get the type of a variable

Python: How to get the type of a variable

This tutorial will show you:

  1. How to get the type of a variable.
  2. How to print the name of the type
  3. How to check if a variable is a specific type.

How to get the type of a variable

To get the type of a variable, we need to use the type() function.
Type() is a built-in function that returns the type of a given object.

Syntax

type(obj)

 Examples

Let's see some examples of using type():

# List
var = [1, 2, 3]

# Get type of variable
print(type(var))

Output:

<class 'list'>

 

# String
var = "Hello Python"

# Get type of variable
print(type(var))

Output:

<class 'str'>

 

# Function
def test():
    return "Hello Python"

print(type(test))

Output:

<class 'function'>

How to print the name of the type

To print the name of the type, we need to use __name__:

Syntax

type(obj).__name__

Example

# String
var = "Hello Python"

# Get name of type
type_name = type(var).__name__

# Print
print(type_name)

Output:

str

How to check if a variable is a specific type

In this part of the tutorial, we'll see how to check the type of a variable using the type() function. Let's check if the variable is a string.

Example

# String
var = "Hello Python"

# Check if Variable is a string
if type(var) == str:
    print(True)
else:
    print(False)

Output:

True

str is a keyword pointing to the string.