Ben Chuanlong Du's Blog

It is never too late to learn.

Equality by Reference and Value in Python

Below is a summary of equality by reference and value in different programming languages.

In [1]:
import pandas as pd

s = """
	Reference	Value
Python	is	==
R	[1]	==
Java	==	equals
Scala	eq [2]	== or equals [3]
"""
data = [line.split("\t") for line in s.split("\n") if line != ""]
pd.DataFrame(data[1:], columns=data[0])
Out[1]:
Reference Value
0 Python is ==
1 R [1] ==
2 Java == equals
3 Scala eq [2] == or equals [3]

Tips and Tricks

[] and [] are 2 indepedent (empty) list objects with different address. However, () and () are the same (empty) tuple singleton. The reason is that list is mutable while tuple is immutable.

In [1]:
[] is []
Out[1]:
False
In [2]:
[] == []
Out[2]:
True
In [12]:
() is ()
Out[12]:
True
In [11]:
() == ()
Out[11]:
True

Below are more examples.

In [14]:
a = [1, 2, 3]
b = a[:]
a is b
Out[14]:
False
In [15]:
from copy import copy

a = [1, 2, 3]
copy(a) is a
Out[15]:
False
In [18]:
c = (1, 2, 3)
d = c[:]
c is d
Out[18]:
True
In [17]:
c = (1, 2, 3)
copy(c) is c
Out[17]:
True
In [20]:
c = (1, 2, 3)
e = (1, 2, 3)
c is e
Out[20]:
False

Notice that since str is immutable (similar to tuple) in Python, it has similar behavior on equaility to tuple.

In [21]:
f = "ABC"
g = "ABC"
f is g
Out[21]:
True
In [22]:
f = "ABC"
copy(f) is f
Out[22]:
True
In [23]:
f = "ABC"
h = f[:]
f is h
Out[23]:
True
In [ ]:
 

Comments