Use Comparison Operators in Python

InstructorWill Button

Share this video with your friends

Send Tweet

Use comparison operators such as >, <, >=, <=, ==, and != to determine the next actions taken by your Python application. You will also learn how to identify if your object is a specific type, such as integer or string.

Stephen Weiss
~ 4 years ago

When we compare lists is it comparing each position against a comparable position?

So,

[1,2,3] < [4,5,6]

Is really three comparisons:

  1. 1 < 4
  2. 2 < 5
  3. 3 < 6
Stephen Weiss
~ 4 years ago

More precisely, it seems like it's an and statement where all three of the comparisons must be true. Is that right?

Will Buttoninstructor
~ 4 years ago

Hey Stephen, Lists and Tuples are compared lexicographically. To be equal, they must be of the same type, have the same length, and the corresponding elements must be equal. So you're partially right in your example above:

  • all three of the comparisons must be true, plus
  • the types must be the same (i.e. both are lists), and
  • they both have to have the same length You can read more about it here: https://docs.python.org/3/reference/expressions.html#comparisons
Stephen Weiss
~ 4 years ago

Thanks Will!

For what it's worth, I was also pointed to these docs about comparing sequences and other types.

The interesting tidbit here is:

Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.

So I'm actually not sure that your second bullet is required (as long as there are valid comparison methods. That said, not sure how that'd work.

Also, just ran this to test and it returns true:

>>> [1,2,3] < [4,5]
True