How to Check a Variable Type in Python

Updated onbyAlan Morel
How to Check a Variable Type in Python

In Python, you can use variables to store data, pass data between functions, and manipulate data.

This data is held in memory for the duration of the program and is lost when the program ends.

Variables can be of a different type because data comes in many different forms.

In this post, we'll learn about how you can check the type of a variable in Python.

Variable Types in Python

Before we start, let's get familiar with the different types of variables in Python.

Here is the list of them all, and a short description of each:

  • Number: This includes integers, floats, and complex numbers.
  • Boolean: This is either True or False.
  • String: This includes strings, bytes, and Unicode.
  • List: Liosts are a mutable ordered sequence of elements.
  • Tuple: Tuples are immutable ordered sequences of elements.
  • Dictionary: Dictionaries are unordered mapping of keys to values.
  • Set: Sets are unordered collections of unique elements.

With that in mind, let's define some variables and see what types they are.

Using the type() Function

Python has a built-in function called type() that can be used to check the type of a variable.

Simply pass in your variable and it will return the type of the variable.

Let's see this in action.

PYTHON
a = 1 print(type(a)) b = True print(type(b)) c = 1.0 print(type(c)) d = "Hello" print(type(d)) e = [1, 2, 3] print(type(e)) f = (1, 2, 3) print(type(f)) g = {"a": 1, "b": 2} print(type(g))
BASH
<class 'int'> <class 'bool'> <class 'float'> <class 'str'> <class 'list'> <class 'tuple'> <class 'dict'>

Checking the Type of a Variable

If you aren't necessarily interested in the type of the variable, but rather if the variable is of a specific type or not, you can use the isinstance() function.

This function takes in the variable in question, and the type you want to check against, and it will return to you a boolean value if the variable is of that type.

Let's see some examples:

PYTHON
a = 1 print(isinstance(a, int)) b = True print(isinstance(b, str))
BASH
True False

Using this check allows you to proceed with your code safely.

Conclusion

In this post, we learned about the different types of variables in Python.

We also learned how to use the type() function to check the type of a variable and the isinstance() function to check if a variable is of a specific type.

Hopefully, you've found this post helpful and enjoyed it. Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.