Skip to content

Comparisons

A frequent source of confusion for new programmers is the comparison of variable contents. The contents are assigned with = (a single equals sign), while a comparison is made with == (two equals signs) - unlike in maths.

a = 5
b = 10-5
a == b # Results in True

For number types, the comparison operators correspond to the usual understanding:

Operator Meaning Example for True Example for False
== Equal 5 == 5 5 == 6
!= Unequal 5 != 6 5 != 5
< Less than 5 < 6 5 < 5
> Greater than 6 > 5 5 > 5
<= Less than or equal to 5 <= 5 6 <= 5
>= Greater than or equal to 5 >= 5 5 >= 6
a = 5
b = 7
a < b # Returns True
a != b # Returns True
a >= b # Returns False

For strings, the comparison is made lexicographically, i.e. in the order of the alphabet.

Operator Meaning Example for true Example for false
== All characters equal "Hello" == "Hello" "Hello" == "hello"
!= At least one character different "hello" != "Hello" "hello" != "hello"
< Lexicographically smaller than "apple" < "banana" "banana" < "apple"
> Lexicographically greater than "banana" > "apple" "apple" > "banana"
<= Lexicographically less than or equal to "apple" <= "apple" "banana" <= "apple"
>= Lexicographically greater than or equal to "apple" >= "apple" "apple" >= "banana"

Please note that capital letters are entered first:

"Apple" < "apple" # Returns True

If a string begins with another, the shorter one is sorted first. However, the length is only considered secondarily:

"Foot" < "Football" # Returns True
"Food" < "Foot" # Returns True

In general, alphabetical sorting of strings has a lot of pitfalls and is therefore not dealt with further here.

Identity comparison

Now it gets a little more complicated. The identity comparison (operator is) checks whether two variables point to the same object in the memory. This is not the same as the value comparison (which is carried out with ==). This comparison is mainly relevant for objects and should not be used for numbers and character strings:

a = 5
b = 5
a == b # Returns True
a is b # Returns True

a = 5**4
b = 5**4
a == b # Returns True
a is b # Returns False

At first glance, the two numbers look the same, but they are not the same object in memory. This is because Python always uses the same object in memory for small numbers (between -5 and 256). Therefore, an identity comparison for numbers does not make sense.