In Python, is and == are both comparison operators that can be used to check if two values are equal. However, there are some important differences between the two of them.
is
operator compares the identity of two objects, while
==
operator compares the values of the objects.
Dataview (inline field '='): Error: -- PARSING FAILED -------------------------------------------------- > 1 | = | ^ Expected one of the following: '(', 'null', boolean, date, duration, file link, list ('[1, 2, 3]'), negated field, number, object ('{ a: 1, b: 2 }'), string, variable
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True
print(a is b) # False
==
returns True. is
returns False.Dataview (inline field '='): Error: -- PARSING FAILED -------------------------------------------------- > 1 | = | ^ Expected one of the following: '(', 'null', boolean, date, duration, file link, list ('[1, 2, 3]'), negated field, number, object ('{ a: 1, b: 2 }'), string, variable
One important thing to note is that, in Python, strings and integers are immutable, which means that once they are created, their value cannot be changed.
This means that, for strings and integers, is and ==
will always return the same result:
Dataview (inline field '='): Error: -- PARSING FAILED -------------------------------------------------- > 1 | = | ^ Expected one of the following: '(', 'null', boolean, date, duration, file link, list ('[1, 2, 3]'), negated field, number, object ('{ a: 1, b: 2 }'), string, variable
a = "hello"
b = "hello"
print(a == b) # True
print(a is b) # True
a = 5
b = 5
print(a == b) # True
print(a is b) # True
In these cases, a and b are both pointing to the same object in memory, so is and == both return True.
For mutable objects such as lists & dictionaries, is
and ==
can behave differently.
Dataview (inline field '='): Error: -- PARSING FAILED -------------------------------------------------- > 1 | = | ^ Expected one of the following: '(', 'null', boolean, date, duration, file link, list ('[1, 2, 3]'), negated field, number, object ('{ a: 1, b: 2 }'), string, variable
In general:
- Use ==
when you want to compare the values of two objects, and
- Use is
when you want to check if two objects are the same object in memory.
Dataview (inline field '='): Error: -- PARSING FAILED -------------------------------------------------- > 1 | = | ^ Expected one of the following: '(', 'null', boolean, date, duration, file link, list ('[1, 2, 3]'), negated field, number, object ('{ a: 1, b: 2 }'), string, variable