Home > Backend Development > Python Tutorial > How Does Python 2 Compare Objects of Different Types?

How Does Python 2 Compare Objects of Different Types?

Mary-Kate Olsen
Release: 2024-12-17 04:48:24
Original
547 people have browsed it

How Does Python 2 Compare Objects of Different Types?

How Object Comparison Works in Python 2

Python 2's behavior when comparing objects of different types can be confusing, but it's based on implementation details provided by the language specification.

Implementation-Specific Behavior

When comparing objects of different types, Python 2 uses the following order:

  • Numerics first: Numeric types (integers, floats) take precedence over non-numerics.
  • Lexicographic ordering for strings: Strings are compared lexicographically.
  • Type name ordering for non-numerics: Objects of the same type but with no proper comparison methods are ordered by their type names, sorted alphabetically.

Examples

To illustrate:

print "100" < "2"      # True (lexicographic)
print "5" > "9"        # False (lexicographic)

print "100" < 2        # False (numeric first)
print 100 < "2"        # True (numeric first, lexicographic second)

print 5 > "9"          # False (lexicographic)
print "5" > 9          # True (numeric first, lexicographic second)

print [] > float('inf') # True (non-numeric ordering)
print () > []          # True (non-numeric ordering)
Copy after login

Implementation Details

This behavior is mandated by the CPython implementation of Python 2. The language spec states that objects of different types are ordered "arbitrarily but consistently," leaving the details up to the implementation.

Differences Between Versions and Implementations

In Python 3, comparisons between integers and strings raise an error. Other implementations of Python may also have slightly different behavior.

The above is the detailed content of How Does Python 2 Compare Objects of Different Types?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template