Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Equality by Reference and Value in Python

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

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

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])
Loading...

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.

[] is []
False
[] == []
True
() is ()
True
() == ()
True

Below are more examples.

a = [1, 2, 3]
b = a[:]
a is b
False
from copy import copy

a = [1, 2, 3]
copy(a) is a
False
c = (1, 2, 3)
d = c[:]
c is d
True
c = (1, 2, 3)
copy(c) is c
True
c = (1, 2, 3)
e = (1, 2, 3)
c is e
False

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

f = "ABC"
g = "ABC"
f is g
True
f = "ABC"
copy(f) is f
True
f = "ABC"
h = f[:]
f is h
True