Object Value vs Object Type vs Object Id in Python

Python Beginners Guide📚

Learn about identity comparison vs equality comparison (is vs ==)

Photo by Magda Ehlers from Pexels

Objects in Python

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects.

Every object has

  • identity
  • type
  • value.

Topics covered in this story

 

Photo by Author

Object Id vs Object Type vs Object value

 

Photo by Author
a=5
print (type(5))#Output:<class 'int'>
print (id(a))#Output:1613096944

b="hello"
print (type(b))#Output:<class 'str'>
print (id(b))#Output:53076544

Object Identity

An object’s identity never changes once it has been created. You may think of it as the object’s address in memory.

id() function

Syntax: id(object)

  • Returns the identity of an object.
  • It is an integer that is unique and constant for this object during its lifetime.
  • Two objects with non-overlapping lifetimes may have the same id() value.
  • CPython implementation detail: This is the address of the object in memory.

Example: Let’s find the id of python data types strings, list, tuple, dictionary.

a=5
print (id(a))#Output:1441654768

l=[1,2,3]
print (id(l))#Output:12597256

t=(1,2,3)
print (id(t))#Output:44739208

d={'a':1,'b':2}
print (id(d))#Output:12532704

s="python"
print (id(s))#Output:45025152

How to do identity comparisons:

is operator

The is operator is used to compare the identity of two objects.

x is y is True if and only if x and y are the same objects.

id(x)==id(y) is True if and only x and y are the same object.

Example:

x=5
y=5
print (x is y)#Output:True
print (id(x)==id(y))#Output:True
print (id(x))#Output:1441654768
print (id(y))#Output:1441654768

Pictorial Representation

Immutable data types:

For immutable datatype, operations that compute new values may actually return a reference to any existing object with the same type and value.

Ex. a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation

Mutable data types:

For mutable data types, this is not allowed.

c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists.

Example:

c=[1,2]
d=[1,2]
print (c is d)#Output:False
print (id(c))#Output:16857096
print (id(d))#Output:47485256

print (id(c[0]))#Output:1441654704
print (id(c[1]))#Output:1441654720
print (id(d[0]))#Output:1441654704
print (id(d[1]))#Output:1441654720

Pictorial Representation

 

Photo by Author

Containers are some objects which contain references to other objects. Examples of containers are tuples, lists, and dictionaries. The references are part of a container’s value.

List contains only references to objects. Since the list is a mutable object, two lists will not have the same id even if the elements are the same.


Object Type

The type() function returns an object’s type (which is an object itself). Like its identity, an object’s type is also unchangeable.

a=5
print (type(a))#Output:<class 'int'>

b=5.0
print (type(b))#Output:<class 'float'>

l1=[1,2]
print (type(l1))#Output:<class 'list'>

t1=(1,2)
print (type(t1))#Output:<class 'tuple'>

d1={'a':1,'b':2}
print (type(d1))#Output:<class 'dict'>

How to test the type of an object.

The isinstance() built-in function is recommended for testing the type of an object.

Syntax:
isinstance(object,classinfo)

Return True if the object argument is an instance of the classinfo argument.

If object is not an object of the given type, the function always returns False

print (isinstance(5,float))#Output:False
print (isinstance(5,int))#Output:True
print (isinstance([1,2],list))#Output:True
print (isinstance([1,2],tuple))#Output:False

Syntax: isinstance(object,classinfo)

If classinfo is a tuple of type objects, return True if the object is an instance of any of the types.

If classinfo is not a type or tuple of types and such tuples, an exception is raised.

print (isinstance(([1,2],1),(list,tuple)))#Output:True
print (isinstance([1,2],(float,list)))#Output:True

print (isinstance([1,2],integer))
#Output:NameError: name 'integer' is not defined

Object Value

The object value of some objects can change.
Objects whose value can change are said to be mutable.
Objects whose value is unchangeable once they are created are called immutable.

An object’s mutability is determined by its type.

Numbers, strings, and tuples are immutable.
Dictionaries and lists are mutable.

The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however, the container is still considered immutable because the collection of objects it contains cannot be changed.

Ex. A tuple is an immutable object but it can contain mutable elements like a list.

t=([1,2],3)
#If a tuple element contains list, we can modify that.
t[0][1]=3
print (t)#Output:([1, 3], 3)

Equality Comparisons:

Equality comparisons are done by == operator.

It compares the value of two objects. The objects do not need to have the same type.

c=1
s=1.0
print (type(c))#Output:<class 'int'>
print (type(s))#Output:<class 'float'>
print (c==s)#Output:True

Sequences (instances of tuple, list, or range) can be compared only within each of their types. Equality comparison across these types results in inequality.

For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is False because the type is not the same).

l1=[1,2]
t1=(1,2)
print (l1==t1)#Output:False

Identity vs Equality Comparison(is vs ==)

is operator compares the identity of two objects

== operator compares the value of two objects.

Identical objects should compare equal.

  • x is y implies x == y
l1=[1,2]
l2=[1,2]
#"==" checks the value. both l1 and l2 contains same values.
print (l1==l2)#Output:True
#"is" checks for identity.Both l1 and l2 are different list objects
print (l1 is l2)#Output: False
print (id(l1))#Output:46086152
print (id(l2))#Output:47681832

Conclusion:

  • In Python, each object has an identity, type, and value.
  • id() function returns the identity of the object.
  • type()function returns the type of the object.
  • is operator compares the identity of two objects.== operator compares the value of two objects.

I hope that you have found this article helpful, thanks for reading!


Resources(Python Documentation):

Object, Values,Types

Identity Comparisons

id(object)

Value Comparisons

isinstance()

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s