Well, there is this part in docs explaining your problem:
This does not give minimal editing sequences, but usually gives matches that โlook rightโ for people.
You can use Levenshtein_distance to get the expected results.
But for comparing IP addresses, I would suggest using integer comparison:
>>> parts = [int(s) for s in '198.124.252.130'.split('.')] >>> parts2 = [int(s) for s in '198.124.252.101'.split('.')] >>> from operator import sub >>> diff = sum(d * 10**(3-pos) for pos,d in enumerate(map(sub, parts, parts2))) >>> diff 29
This style can be used to create a comparison function:
from functools import partial from operator import sub def compare_ips(base, ip1, ip2): base = [int(s) for s in base.split('.')] parts1 = (int(s) for s in ip1.split('.')) parts2 = (int(s) for s in ip2.split('.')) test1 = sum(abs(d * 10**(3-pos)) for pos,d in enumerate(map(sub, base, parts1))) test2 = sum(abs(d * 10**(3-pos)) for pos,d in enumerate(map(sub, base, parts2))) return cmp(test1, test2) base = '198.124.252.101' test_list = ['198.124.252.102','134.55.41.41','134.55.219.121', '134.55.219.137','134.55.220.45', '198.124.252.130'] sorted(test_list, cmp=partial(compare_ips, base)) # yields: # ['198.124.252.102', '198.124.252.130', '134.55.219.121', '134.55.219.137', # '134.55.220.45', '134.55.41.41']