Identity Operators
We'll cover the following
Identity operators
Name | Symbol | Syntax | Explanation |
Is operator | is |
| Returns |
Is not operator | is not |
| Returns |
For demonstration purposes, let’s take two variables. First we’ll set var_one
to [1, 2, 3]
and var_two
to [1, 2, 3]
as well. Applying the above identity operators would give the following results:
The is
operator
True
if var_one
is the same object as var_two
; otherwise it’s False
.
Expression: The list [1, 2, 3]
is the same object as the other list [1, 2, 3]
, which is False
.
The is not
operator
True
if var_one
is not the same object as var_two
; otherwise it’s False
.
Expression: The list [1, 2, 3]
is not the same object as the other list [1, 2, 3]
, which is True
.
Even though the values may be the same, the object instances are different.
Code
We can put this effectively into Python code, and you can even change the variables and experiment with the code yourself! Click on the “Run” button to see the output.
var_one = [1, 2, 3]var_two = [1, 2, 3]result_is = var_one is var_twoprint(result_is)result_is_not = var_one is not var_twoprint(result_is_not)
Same data type values can be compared among themselves, and if the values are the same, the is
operator returns True
as well.
bool_one = Truebool_two = Falseresult_is = bool_one is bool_twoprint(result_is)result_is_not = bool_one is not bool_twoprint(result_is_not)num_one = 5num_two = 5result_is = num_one is num_twoprint(result_is)result_is_not = num_one is not num_twoprint(result_is_not)
Note: Although
1
orTrue
as well as0
orFalse
essentially represent the same thing (and the==
operator considers them equal), theis
operator will not consider them equal since they have distinct data types.