5.8. Object Identity

5.8.1. Rationale

  • == checks for object equality

  • is checks for object identity

found = True

found is True
found == True

5.8.2. Identity

  • id(obj) -> int

  • id() will change every time you execute script

  • id() returns an integer which is guaranteed to be unique and constant for object during its lifetime

  • Two objects with non-overlapping lifetimes may have the same id() value

  • In CPython it's also the memory address of the corresponding C object

# 4499664048

# '0x10c336cb0'

5.8.3. Compare Value and Identity

>>> a = 'Mark Watney'
>>> b = 'Mark Watney'

>>> a == b
>>> a is b
>>> a = 'Mark Watney'
... b = 'Mark Watney'

>>> a == b
>>> a is b

5.8.4. Value Comparison

  • == checks for object equality

'Mark Watney' == 'Mark Watney'
# True

5.8.5. Identity Check

  • is checks for object identity

  • Compares id() output for both objects

  • CPython: compares the memory address a object resides in

  • Is used for checking if None

  • Testing strings with is only works when the strings are interned

Changed in version Python: 3.8 Compiler produces a SyntaxWarning when identity checks (is and is not) are used with certain types of literals (e.g. str, int). These can often work by accident in CPython, but are not guaranteed by the language spec. The warning advises users to use equality tests (== and !=) instead.

'Mark Watney' is 'Mark Watney'
# <stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
# True
name = None

if name is None:
    print('Your name is empty')
    print(f'Hello {name}')

5.8.6. Assignments


Create assignments