Predictive Hacks

How to Check the Data Type in an if Statement

In Python we can get the data types of an object with the type command (type(object)). For example:

x = 5
type(x)
int
x = [1,2,3]
type(x)
list

However, this approach does not work in the if statements as we can see below:

x = [1,2,3]
if type(x)=='list':
    print("This is a list")

else:
    print("I didn't find any list")
I didn't find any list

For that reason, we should work with the isinstance(object, type) function. For example:

x = [1,2,3]
if isinstance(x, list):
    print("This is a list")

elif isinstance(x, int):
    print("This is an integer")
    
else:
    print("This is neither list nor integer")
This is a list
x = 5
if isinstance(x, list):
    print("This is a list")

elif isinstance(x, int):
    print("This is an integer")
    
else:
    print("This is neither list nor integer")
This is an integer
x = "5"
if isinstance(x, list):
    print("This is a list")

elif isinstance(x, int):
    print("This is an integer")
    
else:
    print("This is neither list nor integer")
This is neither list nor integer

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s