Python 3.3+ipaddressfunction
ipaddress.get_mixed_type_key()
range operations
A key function for sorted() that lets you order a mix of IPv4 and IPv6 addresses and networks.
Syntax
sorted(items, key=ipaddress.get_mixed_type_key)
A plain sorted() on such a list fails with TypeError ('are not of the same version' or "'<' not supported"): addresses and networks of different versions are not comparable. With key=get_mixed_type_key IPv4 comes before IPv6 and a network before the addresses inside it, except its own network address, which comes first. Pass the function itself, without parentheses.
Examples
import ipaddress
items = [ipaddress.ip_address('::1'), ipaddress.ip_address('10.0.0.1'),
ipaddress.ip_network('10.0.0.0/8')]
print([str(x) for x in sorted(items, key=ipaddress.get_mixed_type_key)])
# → ['10.0.0.0/8', '10.0.0.1', '::1']
sorted(items) # → TypeError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy