Home » Python

How to determine a Python variable's type?

Here, we are going to learn how to determine the type of a variable in Python programming language? We will also learn the comparison about type() and isinstance() methods.
Submitted by Sapna Deraje Radhakrishna, on December 04, 2019

There are two inbuilt methods available in python to determine the variable's type.

1) type() method

If a single argument is passed to type(), it returns type of the given object.

Syntax:

    type(object)

Example:

>>> test_string = "yes"
>>> test_number = 1
>>> print(type(test_string))
<class 'str'>
>>> print(type(test_number))
<class 'int'>

2) isinstance() method

The isinstance() function checks if the object (first argument ) is an instance or subclass of classinfo class (second argument)

Syntax:

    isinstance(object, classinfo)

Here, object: object to be validated, and classinfo: class, type, or tuple of classes and types

Return value: true if the object is an instance or subclass of a class, or any element of the tuple, false otherwise. If the classinfo is not a type or a tuple of types, a TypeError exception is raised.

Example:

>>> class Example:
...     name = 'include_help'
...
>>> ExampleInstance = Example()
>>> print(isinstance(ExampleInstance, Example))
True
>>> print(isinstance(ExampleInstance, (list, set)))
False
>>> print(isinstance(ExampleInstance, (list, set, Example)))
True
>>>

Comparison between type() and isinstance()

type() isinstance()
It returns the type object of an object and comparing what it returns to another type object will only return True when the same type object are on both sides. In order to see if an object has a certain type, use isinstance() as it checks to see if the object passed in the first argument is of the type of any of the type objects passed in the second argument. Hence, it works as expected with subclassing and old-style classes, all of which have the legacy type object instance.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.