Compare Version Numbers in Python

Comparing version numbers is a common programming task. Python provides several ways to compare version strings like "1.0.1" and "1.2.3". When comparing versions, we return 1 if the first version is greater, -1 if it's smaller, and 0 if they're equal.

Understanding Version Number Comparison

Version numbers consist of numeric parts separated by dots. Each part represents a different level of revision ?

  • Version "2.5" means the 5th second-level revision of the 2nd first-level revision

  • Missing parts default to 0 (e.g., "1.2" is equivalent to "1.2.0.0...")

  • Compare each part from left to right until finding a difference

Method 1: Manual Implementation

Split version strings into numeric parts and compare them level by level ?

def compare_version(version1, version2):
    # Split versions into numeric parts
    v1_parts = [int(v) for v in version1.split(".")]
    v2_parts = [int(v) for v in version2.split(".")]
    
    # Compare each part
    max_length = max(len(v1_parts), len(v2_parts))
    for i in range(max_length):
        # Get part value or 0 if missing
        v1 = v1_parts[i] if i < len(v1_parts) else 0
        v2 = v2_parts[i] if i < len(v2_parts) else 0
        
        if v1 > v2:
            return 1
        elif v1 < v2:
            return -1
    
    return 0

# Test examples
print(compare_version("1.0.1", "1.0"))
print(compare_version("1.2", "1.2.3"))
print(compare_version("2.0", "1.9.9"))
1
-1
1

Method 2: Using packaging Module

The packaging module provides built-in version comparison functionality ?

from packaging import version

def compare_version_packaging(version1, version2):
    v1 = version.parse(version1)
    v2 = version.parse(version2)
    
    if v1 > v2:
        return 1
    elif v1 < v2:
        return -1
    else:
        return 0

# Test examples
print(compare_version_packaging("1.0.1", "1.0"))
print(compare_version_packaging("1.2", "1.2.3"))
print(compare_version_packaging("2.0.1", "2.0.1"))
1
-1
0

Method 3: Using distutils (Legacy)

For older Python versions, you can use distutils.version ?

from distutils.version import LooseVersion

def compare_version_distutils(version1, version2):
    v1 = LooseVersion(version1)
    v2 = LooseVersion(version2)
    
    if v1 > v2:
        return 1
    elif v1 < v2:
        return -1
    else:
        return 0

# Test example
print(compare_version_distutils("1.0.1", "1.0"))

Comparison of Methods

Method Pros Cons Best For
Manual Implementation No dependencies, full control More code to maintain Simple version formats
packaging module Robust, handles complex versions External dependency Production applications
distutils (deprecated) Built-in to Python Deprecated in Python 3.10+ Legacy code only

Edge Cases to Consider

Version comparison can handle various edge cases ?

def test_edge_cases():
    test_cases = [
        ("1.0", "1.0.0"),      # Missing parts
        ("1.01", "1.1"),       # Leading zeros
        ("1.0.0", "1"),        # Different lengths
        ("2.0", "1.9.9.9"),    # Major version difference
    ]
    
    for v1, v2 in test_cases:
        result = compare_version(v1, v2)
        print(f"{v1} vs {v2}: {result}")

test_edge_cases()
1.0 vs 1.0.0: 0
1.01 vs 1.1: 0
1.0.0 vs 1: 0
2.0 vs 1.9.9.9: 1

Conclusion

Use the manual implementation for simple version comparison or the packaging module for robust production applications. The manual method gives you full control while external libraries handle complex version formats and edge cases automatically.

Updated on: 2026-03-25T08:35:19+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements