Know the type() and check the id() in Python

I love both the type and the id commands in Python. They are self explanatory and can save you from a lot of trouble.

For example, you want to create an one item tuple containing “one” and combine with another tuple containing (9,9,0). See the code below.

>>> tuple1=(9,9,1)
>>> tuple2=(“one”)
>>> tuple3=tuple1+tuple2
Traceback (most recent call last):
File “<pyshell#237>”, line 1, in <module>
tuple3=tuple1+tuple2
TypeError: can only concatenate tuple (not “str”) to tuple
>>>

What! we have a syntax error! What went wrong? use the type() command to find out!!

>>> type(tuple1)
<class ‘tuple’>
>>> type(tuple2)
<class ‘str’>

Oh, ho! Tuple 2 is a string object!! How! Well, we missed a comma! Correct the codes now.

>>> tuple1
(9, 9, 1)
>>> tuple2=(“one”,) #notice the use of comma
>>> type(tuple2)
<class ‘tuple’>
>>> tuple3=tuple1+tuple2
>>> type(tuple3)
<class ‘tuple’>
>>> id(tuple1)
47481200
>>> id(tuple2)
47534800
>>> id(tuple3)
47577968
>>>

The id() function is used to return the memory¬†address of an object, which I normally don’t use much, but I use the type() command most frequently. It helps me a lot debugging my codes. Sometimes, you can use the id() command to prove immutability of numbers in python. In other words, if you change the variable value, a new memory address will be created.

>>> var1=20
>>> id(var1)
505911168
>>> var1=40
>>> id(var1)
505911488

You can apply the same principle to lists. As lists are mutable, adding or deleting content does not change their memory address.

>>> alist=[1,2,3,4,5]
>>> id(alist)
33806976
>>> alist.append(30)
>>> alist
[1, 2, 3, 4, 5, 30]
>>> id(alist)
33806976
>>> alist.pop()
30
>>> alist
[1, 2, 3, 4, 5]
>>> id(alist)
33806976
>>>

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *