Python Glossary Русский

Python 3.3+ipaddressfunction

ipaddress.collapse_addresses()

range operations

Merges a list of networks and addresses into the minimal set of networks: adjacent and overlapping ranges are combined.

Syntax

ipaddress.collapse_addresses(addresses)

It returns a generator, not a list: print() shows <generator object ...>, and a second pass over the result is empty, so wrap it in list(). Single addresses are accepted and become /32 networks. Mixing IPv4 and IPv6 in one call raises TypeError; collapse them separately.

Examples

import ipaddress
nets = [ipaddress.ip_network('10.0.0.0/25'), ipaddress.ip_network('10.0.0.128/25'),
        ipaddress.ip_network('10.0.1.0/24')]
print(list(ipaddress.collapse_addresses(nets)))  # → [IPv4Network('10.0.0.0/23')]
addrs = [ipaddress.ip_address('10.0.0.1'), ipaddress.ip_address('10.0.0.0')]
print(list(ipaddress.collapse_addresses(addrs)))  # → [IPv4Network('10.0.0.0/31')]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy