Elessar Elessar - 27 days ago 15
Python Question

Python-reverse=True reversing issue

def last_name(str):
return str.split()[1]
names=["Isaac Newton","Fred Newton","Niels Bohr"]
print("s:",sorted(names,key=last_name))
print("s:",sorted(names,key=last_name,reverse=True))


Output:

s: ['Niels Bohr', 'Isaac Newton', 'Fred Newton']
s: ['Isaac Newton', 'Fred Newton', 'Niels Bohr']


When i use
reverse=True
, shouldn't it be like this :
['Fred Newton','Isaac Newton', 'Niels Bohr']
?

Answer

Python's sorting algorithm is stable. If two values have the same key(value) results, then their relative order is kept the same. Reversing only applies to key(value) results that differ.

Because key('Isaac Newton') and key('Fred Newton') both produces 'Newton', these two strings are left in their original relative order. The reverse=True flag only influences if 'Bohr' is sorted before or after 'Newton'.

Comments