SeanPlusPlus
SeanPlusPlus

Reputation: 9033

Difference between comparing dictionaries in Python versus comparing objects in JavaScript

Reading through this really cool online book, Speaking JS, I came across a neat quirk illustrating how comparisons work in JavaScript:

Primitive values are "Compared by value":

> 3 === 3
true
> 'abc' === 'abc'
true

Objects, however, are "Compared by reference":

> {} === {}  // two different empty objects
false
> var obj1 = {};
> var obj2 = obj1;
> obj1 === obj2
true

A co-worker and I were chatting about this and wondered if the principle holds for Python.

So we cracked open a Python interpreter to see if this comparison works differently in that language.

>>> 3 == 3
True
>>> {} == {}
True

Turns out, two dictionaries resolve as equal in Python if their contents are the same.

Does this mean that Python dictionaries are "Compared by value"?

Is there a way to compare Python dictionaries by reference?

Upvotes: 0

Views: 88

Answers (1)

Qantas 94 Heavy
Qantas 94 Heavy

Reputation: 16020

In Python, the == operator compares by value. According to the Python 2.7 documentation:

The operators is and is not test for object identity.

See the following example:

print({} is {}) # False
print({} == {}) # True

As Ignacio Vazquez-Abrams said, note that this does not necessarily hold for all values. For example, 9 is 9 is true in some implementations, but don't count on it. Basically, the reason why is that number values may be simply a reference to a single object for all references of the same value, or separate objects . For example, CPython uses references for numbers between -5 and 256, inclusive (for a more detailed explanation, see this question).

print(9 is 9) # dependent on implementation
print(9 == 9) # True

Upvotes: 4

Related Questions