sorting on IP addresses

Jacob Kaplan-Moss jacobkm at
Mon Feb 5 17:46:07 EST 2001

In article <3A7F26CB.BE85C96F at>, Sam Wun <swun at> 
> Hi,
> Does anyone know what is the quickly way to sort a list of IP addresses?
> ie. should be larger than
> Thanks
> Sam

Sam --

Not sure about quick, but this is the way I've been doing it.  If any of 
the gurus out there would like to point out a better method, I would be 
happy to read it.

iplist = ["",

def ip_compare( a, b ):
   """a and b are valid IP addresses of the form w.x.y.z."""
   la = [int(n) for n in a.split(".")]
   lb = [int(n) for n in b.split(".")]
   for pair in zip(la, lb):
      if pair[0] > pair[1]:
         return -1
      elif pair[0] < pair[1]:
         return 1
   return 0
print iplist

Hope that helps, 


More information about the Python-list mailing list