ZetCode

Python radix sort

last modified November 18, 2026 Python 3.15

In this article we explain the radix sort algorithm in Python. We implement the least significant digit (LSD) version with buckets and with counting sort, use binary digits, handle negative numbers, and sort strings and IP addresses.

Radix sort is a non-comparison sort. It sorts integers or strings by processing them one digit or character at a time. It was used to sort punched cards on tabulating machines long before electronic computers existed.

Radix sort algorithm

LSD radix sort starts with the least significant digit. It distributes the numbers into ten buckets by their last digit and collects them back in bucket order. Then it repeats the process for the tens digit, the hundreds digit, and so on. Each pass must be stable: numbers with the same digit keep the order from the previous pass. After the pass on the most significant digit, the list is sorted.

PropertyValue
TimeO(d · (n + b)), d digits in base b
Extra spaceO(n + b)
Stableyes
Requirementkeys that split into digits: integers, fixed-length strings

Radix sort example

The following is an LSD radix sort for non-negative integers with ten buckets.

radix_sort.py
def radix_sort(vals):
    if not vals:
        return vals
    exp = 1
    while max(vals) // exp > 0:
        buckets = [[] for _ in range(10)]
        for v in vals:
            buckets[v // exp % 10].append(v)
        vals = [v for bucket in buckets for v in bucket]
        exp *= 10
    return vals


nums = [170, 45, 75, 90, 802, 24, 2, 66]
print(radix_sort(nums))

The variable exp selects the digit: 1 for units, 10 for tens, and so on. The expression v // exp % 10 extracts that digit. Appending to the buckets keeps the order of the previous pass, which makes each pass stable. The nested comprehension flattens the buckets into a list. The loop ends when exp exceeds the maximum.

$ python radix_sort.py
[2, 24, 45, 66, 75, 90, 170, 802]

Tracing the passes

We print the list after each pass.

radix_trace.py
def radix_sort(vals):
    exp = 1
    while max(vals) // exp > 0:
        buckets = [[] for _ in range(10)]
        for v in vals:
            buckets[v // exp % 10].append(v)
        vals = [v for bucket in buckets for v in bucket]
        print(f'digit {exp:>3}: {vals}')
        exp *= 10
    return vals


radix_sort([170, 45, 75, 90, 802, 24, 2, 66])

After the first pass, the numbers are sorted by the last digit. After the second one, by the last two digits: 802 and 2 both have 0 in the tens place, and 802 comes first because it came first in the previous pass. After the third pass, the numbers are sorted by all three digits.

$ python radix_trace.py
digit   1: [170, 90, 802, 2, 24, 45, 75, 66]
digit  10: [802, 2, 24, 45, 66, 170, 75, 90]
digit 100: [2, 24, 45, 66, 75, 90, 170, 802]

Radix sort with counting sort

The classic formulation of radix sort uses the stable counting sort for each digit instead of lists of buckets.

counting_digits.py
def counting_sort_by_digit(vals, exp):
    counts = [0] * 10
    for v in vals:
        counts[v // exp % 10] += 1
    for d in range(1, 10):
        counts[d] += counts[d - 1]
    res = [0] * len(vals)
    for v in reversed(vals):
        d = v // exp % 10
        counts[d] -= 1
        res[counts[d]] = v
    return res


def radix_sort(vals):
    if not vals:
        return vals
    exp = 1
    while max(vals) // exp > 0:
        vals = counting_sort_by_digit(vals, exp)
        exp *= 10
    return vals


nums = [329, 457, 657, 839, 436, 720, 355]
print(radix_sort(nums))

After counting, counts[d] holds the number of elements with a digit up to d, which is one past the last position for digit d. The final loop goes through the input backwards and fills each digit's positions from the end; walking backwards keeps equal digits in their original order. The output list is preallocated, so no buckets are created.

$ python counting_digits.py
[329, 355, 436, 457, 657, 720, 839]

Binary digits

The base does not have to be 10. Computers work with bits, so we can use groups of bits as digits and extract them with shifts and masks.

radix_bytes.py
import random


def radix_sort(vals, bits=8):
    if not vals:
        return vals
    mask = (1 << bits) - 1
    shift = 0
    passes = 0
    while max(vals) >> shift:
        buckets = [[] for _ in range(1 << bits)]
        for v in vals:
            buckets[(v >> shift) & mask].append(v)
        vals = [v for bucket in buckets for v in bucket]
        shift += bits
        passes += 1
    return vals, passes


rng = random.Random(15)
data = [rng.randrange(2**32) for _ in range(100_000)]

for bits in (1, 4, 8, 16):
    res, passes = radix_sort(data, bits)
    assert res == sorted(data)
    print(f'{bits:>2}-bit digits: {1 << bits:>5} buckets, {passes:>2} passes')

The expression (v >> shift) & mask extracts a group of bits bits. For 32-bit numbers, single bits need 32 passes, bytes need four, and 16-bit digits only two, but with 65,536 buckets. A larger base means fewer passes but more buckets; 8 bits is a common compromise.

$ python radix_bytes.py
 1-bit digits:     2 buckets, 32 passes
 4-bit digits:    16 buckets,  8 passes
 8-bit digits:   256 buckets,  4 passes
16-bit digits: 65536 buckets,  2 passes

Negative numbers

Digit extraction does not work on negative numbers in the usual way. One solution is to sort the negative and the non-negative numbers separately.

negative.py
def radix_sort(vals):
    if not vals:
        return vals
    exp = 1
    while max(vals) // exp > 0:
        buckets = [[] for _ in range(10)]
        for v in vals:
            buckets[v // exp % 10].append(v)
        vals = [v for bucket in buckets for v in bucket]
        exp *= 10
    return vals


def radix_sort_signed(vals):
    neg = radix_sort([-v for v in vals if v < 0])
    pos = radix_sort([v for v in vals if v >= 0])
    return [-v for v in reversed(neg)] + pos


temps = [12, -5, 0, 23, -17, 8, -1, 31, -5]
print(radix_sort_signed(temps))

We negate the negative numbers, sort their absolute values, and reverse the result, because a larger absolute value means a smaller negative number. The sorted negative numbers come before the non-negative ones.

$ python negative.py
[-17, -5, -5, -1, 0, 8, 12, 23, 31]

Sorting fixed-length strings

LSD radix sort also works for strings of the same length, such as codes or licence plates. The characters are the digits.

strings_lsd.py
def lsd_sort(words, width):
    for pos in range(width - 1, -1, -1):
        buckets = {}
        for w in words:
            buckets.setdefault(w[pos], []).append(w)
        words = [w for ch in sorted(buckets) for w in buckets[ch]]
        print(f'position {pos}: {words}')
    return words


plates = ['BA123', 'KE456', 'BA045', 'ZA123', 'KE120', 'BL999']
lsd_sort(plates, 5)

The passes go from the last character to the first. A dictionary serves as buckets, and only the characters that actually occur are sorted to get the bucket order. In the last pass, BA045 and BA123 share the first character and keep the order established by the previous passes.

$ python strings_lsd.py
position 4: ['KE120', 'BA123', 'ZA123', 'BA045', 'KE456', 'BL999']
position 3: ['KE120', 'BA123', 'ZA123', 'BA045', 'KE456', 'BL999']
position 2: ['BA045', 'KE120', 'BA123', 'ZA123', 'KE456', 'BL999']
position 1: ['BA045', 'BA123', 'ZA123', 'KE120', 'KE456', 'BL999']
position 0: ['BA045', 'BA123', 'BL999', 'KE120', 'KE456', 'ZA123']

MSD radix sort for variable-length strings

For strings of different lengths, the most significant digit (MSD) version is a better fit. It distributes the strings by their first character and recursively sorts each bucket by the next character.

strings_msd.py
def msd_sort(words, pos=0):
    if len(words) <= 1:
        return words
    done = [w for w in words if len(w) == pos]
    buckets = {}
    for w in words:
        if len(w) > pos:
            buckets.setdefault(w[pos], []).append(w)
    res = done
    for ch in sorted(buckets):
        res += msd_sort(buckets[ch], pos + 1)
    return res


words = ['she', 'sells', 'sea', 'shells', 'by', 'the', 'sea', 'shore',
         'shell', 'a', 'seashell']
print(msd_sort(words))
print(msd_sort(words) == sorted(words))

Strings that end at the current position come first, because a prefix sorts before its extensions: shell before shells. Each bucket is sorted independently, and buckets with a single string need no further work. The result is the same as with sorted.

$ python strings_msd.py
['a', 'by', 'sea', 'sea', 'seashell', 'sells', 'she', 'shell', 'shells', 'shore', 'the']
True

Sorting IP addresses

An IPv4 address consists of four bytes, so it is a natural key for a radix sort with base 256.

ip_addresses.py
import ipaddress


def radix_sort_records(items, key, digits):
    for d in range(digits - 1, -1, -1):
        buckets = [[] for _ in range(256)]
        for item in items:
            buckets[key(item)[d]].append(item)
        items = [item for bucket in buckets for item in bucket]
    return items


addresses = ['192.168.1.20', '10.0.0.5', '192.168.1.3', '172.16.4.1',
             '10.0.10.1', '8.8.8.8', '192.168.10.1']

print(sorted(addresses))

key = lambda a: [int(octet) for octet in a.split('.')]
print(radix_sort_records(addresses, key, 4))

print(sorted(addresses, key=ipaddress.ip_address))

Sorting the addresses as strings gives the wrong order: 8.8.8.8 comes last and 192.168.1.20 before 192.168.1.3. The radix sort uses the four octets as digits. For simplicity, the key is recomputed in every pass. In practice, the standard library offers a simpler solution: ipaddress.ip_address objects compare numerically.

$ python ip_addresses.py
['10.0.0.5', '10.0.10.1', '172.16.4.1', '192.168.1.20', '192.168.1.3', '192.168.10.1', '8.8.8.8']
['8.8.8.8', '10.0.0.5', '10.0.10.1', '172.16.4.1', '192.168.1.3', '192.168.1.20', '192.168.10.1']
['8.8.8.8', '10.0.0.5', '10.0.10.1', '172.16.4.1', '192.168.1.3', '192.168.1.20', '192.168.10.1']

Benchmark

We compare the byte-based radix sort with sorted on a million numbers with a maximum of 216 and 264.

benchmark.py
import random
import timeit


def radix_sort(vals, bits=8):
    mask = (1 << bits) - 1
    shift = 0
    while max(vals) >> shift:
        buckets = [[] for _ in range(1 << bits)]
        for v in vals:
            buckets[(v >> shift) & mask].append(v)
        vals = [v for bucket in buckets for v in bucket]
        shift += bits
    return vals


rng = random.Random(16)

for limit in (2**16, 2**64):
    data = [rng.randrange(limit) for _ in range(1_000_000)]
    t_radix = timeit.timeit(lambda: radix_sort(data), number=3) / 3
    t_sorted = timeit.timeit(lambda: sorted(data), number=3) / 3
    print(f'max 2**{limit.bit_length() - 1}: radix sort {t_radix:.3f} s,'
          f' sorted {t_sorted:.3f} s')

Although radix sort is linear, our Python version is slower than sorted. Every pass touches all elements in interpreted Python code, and 64-bit numbers need eight passes. Radix sort shines in low-level languages on fixed-size integers; in Python, it is mainly a lesson in algorithm design. The times vary between runs and machines.

$ python benchmark.py
max 2**16: radix sort 0.441 s, sorted 0.224 s
max 2**64: radix sort 2.405 s, sorted 0.435 s

Source

Sorting Techniques – Python documentation

ipaddress – Python documentation

In this article we have implemented LSD and MSD radix sort in Python. See also Python counting sort, Python bucket sort, Python merge sort, and Python sorted function.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.