Sobes.tech
Junior
215

How are sequences compared in Python?

Answer from AI

sobes.tech AI

Sequences in Python (strings, lists, tuples) are compared element by element, starting from the first element.

Comparison algorithm:

  1. The first elements of both sequences are compared.
  2. If the elements are equal, the second elements are compared.
  3. The process continues until unequal elements are found or one of the sequences is exhausted.

The comparison result is determined by the first pair of unequal elements:

  • If the element of the first sequence is "less" than the element of the second sequence, the first sequence is considered smaller.
  • If the element of the first sequence is "greater" than the element of the second sequence, the first sequence is considered larger.

If all elements match and one sequence is a prefix of the other, the longer sequence is considered larger. If both sequences have the same length and all elements match, the sequences are considered equal.

Element types must be comparable. Strings are compared lexicographically (alphabetically). Numbers are compared by value.

Examples:

# String comparison
print("apple" < "banana")  # True, 'a' < 'b'
print("cat" == "cat")      # True
print("dog" > "cat")       # True, 'd' > 'c'

# List comparison
print([1, 2, 3] < [1, 2, 4])  # True, 3 < 4
print([1, 2, 3] == [1, 2, 3])  # True
print([1, 2, 3] > [1, 2])    # True, first is longer

# Tuple comparison
print((1, 2) < (1, 3))      # True, 2 < 3
print((1, 2) == (1, 2))      # True
print((1, 2, 3) > (1, 2))  # True, first is longer

# Types must be comparable
# print([1] < "a") # Error TypeError

Comparison operators:

  • < (less than)
  • > (greater than)
  • <= (less than or equal to)
  • >= (greater than or equal to)
  • == (equal)
  • != (not equal)