bhylu.com

Advertisements

Identity Operators

Identity compares whether two references point to the same object. Equality compares their values according to the object's type. These are related ideas but different tests.

Understand the idea

A newly copied list can be equal to its source without being the same list. An alias points at the original object and observes its mutations. is None is the usual identity test for the unique missing-value sentinel. Do not use is for ordinary strings or numbers just because small examples sometimes seem to work.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

original = [1, 2]
alias = original
copy = original.copy()
print(original == copy)
print(original is copy, original is alias)

Read the result

The outputs are True, then False and True. copy has equal content but independent list identity; alias is another name for original.

Try one change

Append to alias and compare original with copy again. Explain which relationship caused the change to be shared.