Comparison by is vs

suggest change

A common pitfall is confusing the equality comparison operators is and ==.

a == b compares the value of a and b.

a is b will compare the identities of a and b.

To illustrate:

a = 'Python is fun!'
b = 'Python is fun!'
a == b # returns True
a is b # returns False

a = [1, 2, 3, 4, 5]
b = a      # b references a
a == b     # True
a is b     # True
b = a[:]   # b now references a copy of a
a == b     # True
a is b     # False [!!]

Basically, is can be thought of as shorthand for id(a) == id(b).

Beyond this, there are quirks of the run-time environment that further complicate things. Short strings and small integers will return True when compared with is, due to the Python machine attempting to use less memory for identical objects.

a = 'short'
b = 'short'
c = 5
d = 5
a is b # True
c is d # True

But longer strings and larger integers will be stored separately.

a = 'not so short'
b = 'not so short'
c = 1000
d = 1000
a is b # False
c is d # False

You should use is to test for None:

if myvar is not None:
    # not None
    pass
if myvar is None:
    # None
    pass

A use of is is to test for a “sentinel” (i.e. a unique object).

sentinel = object()
def myfunc(var=sentinel):
    if var is sentinel:
        # value wasn’t provided
        pass
    else:
        # value was provided
        pass

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Comparisons:
* Comparison by is vs

Table Of Contents
2 Filter
3 List
7 Loops
9 Comparisons
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve