How To Determine A Python Variable’s Type? – Finxter

0
65
Python type() Function Visual Explanation


Summary: The type() function and the __class__ property enables us to determine the type of a Python variable.


Problem Statement: Determining the type of a variable in Python.

Determining the data type of a variable plays a vital role in programming. Every variable is capable of storing different types of data, and each type has its own use case.

Just like any other programming language, Python also has different data types, which can be broadly categorized as:

  • Numbers/Numeric data types: It contains integers, floating numbers, and complex numbers.
  • String or Text data type: It contains Unicode characters (the set that contains characters and symbols from all languages around the world.)
  • Collections:
    • Tuple: An ordered collection of elements of the different data types. Tuples are immutable, i.e., they cannot be modified afterward.
    • List: An ordered collection of elements of the different data types. They are mutable, i.e., they can be modified afterward.
    • Set: An unordered collection of elements that can store different data types. Sets are immutable and do not allow any duplicate value.
    • Dictionary: A collection that allows us to store data in key-value pairs. Dictionaries are ordered* (in Python 3.6 and earlier dictionaries are unordered), changeable, and do not allow duplicate keys.

NOTE: Python considers everything as an object. Hence, data types are classes, whereas the variables are the object (instance) of these classes. There are different methods to determine the type of variables in Python. Thus, in this article, we are going to learn how to determine Python’s variable type.

Using type() Function

  • type() is a built-in function in Python that proves to be useful while figuring the type of variable utilized in the program in the runtime. The type() function returns the class type of the argument (object) that gets passed as a parameter. 
  • The type() function will contain a variable, and Python will return the data type of that variable. If the argument passed to the function is single, it will return a type of the given object. However, if there are three arguments (name, bases, and dict) passed, it will return a new type object.
Python type() Function Visual Explanation

Example:

# Int variable
a = 100
# Float variable
b = 50.5
# String variable
c = "python"
# List
d = [1, 2, 3, 4, 5]
# Tuple
e = (1, 2, 3, 4, 5)
# Dictionary
f = {1: 'a', 'b': 2, 'c': 3, 4: 'd'}
# type() function with single argument
print("Variable a is of the following data type: ", type(a))
print("Variable b is of the following data type: ", type(b))
print("Variable c is of the following data type: ", type(c))
print("Variable d is of the following data type: ", type(d))
print("Variable e is of the following data type: ", type(e))
print("Variable f is of the following data type: ", type(f))

Output:

Variable a is of the following data type:  <class 'int'>
Variable b is of the following data type:  <class 'float'>
Variable c is of the following data type:  <class 'str'>
Variable d is of the following data type:  <class 'list'>
Variable e is of the following data type:  <class 'tuple'>
Variable f is of the following data type:  <class 'dict'>

🖊️Note: If you want to display only the name of the data type then we have to use the __name__ attribute along with the type() function as follows:

print(type(a).__name__)

Let’s see one more example:

x = 1000000000
print("Variable x is of the following data type:", type(x).__name__)

Output:

Variable x is of the following data type: int

Using __class__

__class__ is a property on a particular object, and it is used to determine the class to which the object belongs.

Example:

# Int variable
a = 100
# Float variable
b = 50.5
# String variable
c = "python"
# List
d = [1, 2, 3, 4, 5]
# Tuple
e = (1, 2, 3, 4, 5)
# Dictionary
f = {1: 'a', 'b': 2, 'c': 3, 4: 'd'}
# __class__ method
print("Variable a is of the following data type: ", a.__class__)
print("Variable b is of the following data type: ", b.__class__)
print("Variable c is of the following data type: ", c.__class__)
print("Variable d is of the following data type: ", d.__class__)
print("Variable e is of the following data type: ", e.__class__)
print("Variable f is of the following data type: ", f.__class__)

Output:

Variable a is of the following data type:  <class 'int'>
Variable b is of the following data type:  <class 'float'>
Variable c is of the following data type:  <class 'str'>
Variable d is of the following data type:  <class 'list'>
Variable e is of the following data type:  <class 'tuple'>
Variable f is of the following data type:  <class 'dict'>

⚠️Caution: It is advisable to not use the __class__  property to check the data type in Python. In Python, generally, the names that begin with underscores (__) are semantically not a piece of the public API. Hence, it is not a good idea for users to not use the __class__ method to determine a variable type in Python unless it is absolutely necessary to do so.

Using The IPython Interpreter

We can also use the IPython interactive interpreter to determine a variable’s type in Python. We need to type the variable name followed by a question mark, and the Python interpreter will return a list of information about the object that includes the type of the object and even the docstring.

Syntax: var?

Example:

x = 10
x?

Output:

How To Determine The Type Of An Object In Python?

Python facilitates us with couple of options to check the type of an object.
(1) type()
(2) isinstance()

Example:

print(type([10, 20, 30]) is list)
print(isinstance([1, 2, 3], list))

Output:

True
True

Related Article: How to Determine the Type of an Object in Python?

How to Iterate through a list and print ‘true’ if the list element is of a certain type?

Yet again the answer to this question is to use type() or isinstance().

# Using type
li = [10, 'twenty', 30]
for i in li:
    if type(i) is int:
        print(i)
# Using isinstance
l = ['One', 2, 'Three']
for i in l:
    if isinstance(i, str):
        print(i)

Output:

10
30
One
Three

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy.

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!



Source link

Leave a reply

Please enter your comment!
Please enter your name here