How about this one. Divide the list into three lists, one with ID < mate , one with ID > mate , and one with mate is None . Then merge the sorted lists, sorted by ID.
I added the __repr__ method for the Ind class for readability of the output.
class Ind(object): def __init__(self,ID,mate): self.ID=ID self.mate=mate def __repr__(self): return 'Ind({},{})'.format(self.ID,self.mate) population=[Ind(8,None), Ind(1,2), Ind(2,3), Ind(2,1), Ind(12,None), Ind(3,2), Ind(10,11), Ind(11,10)] def custom_sort(pop): singles, less, more = [], [], [] for p in pop: if p.mate is None: singles.append(p) elif p.ID < p.mate: less.append(p) elif p.ID > p.mate: more.append(p) comp = lambda x,y: cmp(x.ID,y.ID) return sorted(less,cmp=comp) + sorted(singles,cmp=comp) + sorted(more,cmp=comp,reverse=True) print custom_sort(population)
It is output:
[Ind(1,2), Ind(2,3), Ind(10,11), Ind(8,None), Ind(12,None), Ind(11,10), Ind(3,2), Ind(2,1)]