[Tutor] IP sorting

Roman Suzi rnd@onego.ru
Thu, 27 Dec 2001 10:15:12 +0300 (MSK)

On Thu, 27 Dec 2001, Karthik Gurumurthy wrote:

> this one is cool and so was danny's.
> i have a question here though.
> why do we need to convert to a tuple?
> lot = [tuple(map(int, ip.split("."))) for ip in iplist]
> is there any specific reason. Python does not know to sort a list of lists?

Tuple is a constant list. It is slightly faster to deal with tuples. In my
version I am using standard sort() method, which is much faster "as is"
than when it is using ANY cmp function.

"lot" is a list. I am applying .sort() to it to sort it.

IP adresses has sort order different from their string
representation. Another way to sort them is:

from socket import inet_aton, inet_ntoa

iplist = [

lot = map(inet_aton, iplist)
iplist1 = map(inet_ntoa, lot)

print iplist1


Of course, it is possible to write cmp function as easy as:

def cmpIPAddresses(a, b):
    return cmp(inet_aton(a), inet_aton(b))

That is, one can use the most compact version of IP-addresses

from socket import inet_aton
  iplist.sort(lambda a, b: cmp(inet_aton(a), inet_aton(b)))

Function socket.inet_aton converts symbolical IP-address into 4-byte
string, which can be compared by common rules.

> karthik.

Sincerely yours, Roman A.Suzi
 - Petrozavodsk - Karelia - Russia - mailto:rnd@onego.ru -