⊗pyPmCdOTCh 144 of 208 menu

Checking the type of an object in Python

To check the element type, you need to use the isinstance function. It takes the element as its first parameter, and the type it is being checked for as its second parameter. The names of the functions that convert the data to the corresponding type are taken as the name of the second parameter: for strings - str, numbers - int, lists - list and so on. The isinstance function returns Boolean values: if the element matches the type, it returns True, otherwise - False.

Example

Let's say we have a variable tst. Let's check if its value is a string. To do this, to the right of if, we write the function isinstance. We pass tst and the type str to its parameters. If the value and data type match, then let the corresponding message be displayed:

tst = 'a' if isinstance(tst, str): print('string')

Result of code execution:

'string'

Example

Now let's check if a variable is an integer:

tst = 12 if isinstance(tst, int): print('integer')

Result of code execution:

'integer'

Example

To check whether tst is a floating-point number, the second parameter isinstance should be of type float:

tst = 12.0 if isinstance(tst, float): print('float')

Result of code execution:

'float'

Example

Now let's write a condition to check tst for a list:

tst = [1, 2, 3] if isinstance(tst, list): print('list')

Result of code execution:

'list'

Example

Let's check if a variable is a tuple:

tst = (1, 2, 3) if isinstance(tst, tuple): print('tuple')

Result of code execution:

'tuple'

Example

Now let's set a condition to find out if the variable's value is a dictionary:

tst = {'a': 1, 'b': 2, 'c': 3} if isinstance(tst, dict): print('dictionary')

Result of code execution:

'dictionary'

Practical tasks

Let's say you have a variable. Check if its value is an integer.

Find out if the given variable is a floating point number.

Check if a variable contains a string value.

Check if the given variable is a dictionary.

Check if the given variable is a set.

Check if the given variable is a tuple.

Check if the given variable is a list.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline