Main Content

Identity in Python

Archive - Originally posted on "The Horse's Mouth" - 2013-05-17 07:41:04 - Graham Ellis

There's a differece between "the same", "equal" and "identical". I can have two identical 5p coins, but they're not the same coin. And I can have two coins which are not identical, but are equal in value. And when you're checking for equality in a program, you should know which you're looking at. Take a look at this in Python:

  >>> a = [10]
  >>> b = [10]
  >>> c = a
  >>> a == b
  True
  >>> a is b
  False
  >>> a is c
  True
  >>>


a and b are different lists, but they contain identical information. c is another name for the list which is also called a.

The == operator tells you whether two variables (or expressions) contain equal values, whether or not they're the same actual object.

The is operator tells you whether two variable names point to the same object.

A list (as used above) is a mutable object - something that can be changed within itself. Integers, floats, strings and tuples are immutable - in other words if you want to change something, you need to create a new replacement object. And in Python, identical immutable objects are stored only once for efficiency - so you'll find a different set of results from using is ... if two immutable objects are identical, they'll be the same object. Thus:

  >>> a = 10
  >>> b = 10
  >>> c = a
  >>> a == b
  True
  >>> a is b
  True
  >>> a is c
  True
  >>>