is operator (identity vs ==)
is checks whether two names point to the very same object, while == checks whether two values are equal. Use is mainly with None.
a is b
a is not b
x is None== asks "do these two have the same value?". is asks a stricter question: "are these two names pointing at the very same object in memory?". Two separate lists with the same contents are equal (==) but not identical (is).
The main everyday use of is is checking for None: if result is None:. There is only ever one None object, so is is both correct and clear. The same goes for True and False in the rare cases you need to tell them apart from 1 and 0.
Do not use is to compare numbers or strings. Whether two equal numbers or strings happen to be the same object depends on Python's internal optimisations, which change between versions. Python even warns you when you write x is 5.
Return value
True or False.
Examples
1Equal, but not the same object
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)True False
2Two names for one list
alias = original does not copy anything: both names point at one list, so a change through one shows through the other.
original = ["milk", "eggs"]
alias = original
copy = list(original)
alias.append("bread")
print(original)
print(alias is original, copy is original)
print(copy)['milk', 'eggs', 'bread'] True False ['milk', 'eggs']
list(original) made a new list, so copy kept the old contents.
3Checking for None
def find_user(users, name):
for u in users:
if u == name:
return u
return None
result = find_user(["kim", "lea"], "max")
if result is None:
print("No such user")
print(find_user(["kim", "lea"], "lea") is not None)No such user True
4Why None checks use is
values = [0, "", [], None]
for v in values:
print(repr(v), "falsy:", not v, "| is None:", v is None)0 falsy: True | is None: False '' falsy: True | is None: False [] falsy: True | is None: False None falsy: True | is None: True
if not v: cannot tell 0 or an empty string from None. v is None can.
Common mistakes
Using is to compare values
if name is "Ana": may seem to work in a quick test and then fail with text read from a file or typed by a user. Compare values with ==; keep is for None.
first = "".join(["A", "na"])
print(first == "Ana")
items = [3, 4]
print(items == [3, 4], items is [3, 4])True True False
Writing == None
x == None usually works, but a class can redefine == and make it lie. x is None is the standard, always-correct form.
Questions people ask
When should I use is in Python?
To compare with None (x is None, x is not None), and when you really want to know whether two names point at the same object.
Why does 256 is 256 sometimes give True?
Python reuses some small number objects as a speed trick. It is an internal detail that can change, so never rely on it. Use ==.
How do I see if two variables are the same object?
a is b, or compare id(a) == id(b), which gives the same answer.