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]:
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]:
In [2]:
[] == []
Out[2]:
In [12]:
() is ()
Out[12]:
In [11]:
() == ()
Out[11]:
Below are more examples.
In [14]:
a = [1, 2, 3]
b = a[:]
a is b
Out[14]:
In [15]:
from copy import copy
a = [1, 2, 3]
copy(a) is a
Out[15]:
In [18]:
c = (1, 2, 3)
d = c[:]
c is d
Out[18]:
In [17]:
c = (1, 2, 3)
copy(c) is c
Out[17]:
In [20]:
c = (1, 2, 3)
e = (1, 2, 3)
c is e
Out[20]:
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]:
In [22]:
f = "ABC"
copy(f) is f
Out[22]:
In [23]:
f = "ABC"
h = f[:]
f is h
Out[23]:
In [ ]: