Check Variable Type in Python

Type checking is the process of determining what data type a variable contains. In Python type checking is done using the type() function.

 

The type() Function Syntax

type() accepts three arguments, the first is required and the last two are optional.

 

type(object, bases, dict)

 

  • object – The variable to evaluate (required).
  • bases – Specifies the base classes (optional).
  • dict – Specifies the namespace for the class (optional).

 

Python type() Function Example

To use the Python type() function, pass the variable to evaluate as the first argument:

 

foo = True

print(type(foo))
<class 'bool'>

 

List of Python Data Types

Below is a list of all the data types available in Python:

 

  • Numbers – number data types are float, int and complex
  • List – an indexed collection of items.
  • String – a string of characters.
  • Tuple – an immutable collection of items.
  • Set – a collection of unique items.
  • Dictionary – a collection of key-value pairs.

 

If Variable Data Type Python Example

A common example of type checking in Python is to evaluate the output of the type() function with an if condition. In the example below, we will check if a variable is a list:

 

foo = []

if type(foo) is list:
   print('foo is a list.')
foo is a list.