It performs case insensitive sorting.
Let's modify your example a bit, to include another entry "dan":
lst = ['Ronit', 'Dan', 'dan']
Naturally, you'd expect "Dan" and "dan" to occur together. But they don't, because of the properties of string ordering. Instead, a plain list.sort
call will give you:
lst.sort()
print(lst)
['Dan', 'Ronit', 'dan']
On the other hand, specifying str.lower
gives you this:
lst.sort(key=str.lower)
print(lst)
['Dan', 'dan', 'Ronit']
Here, the original list elements are sorted with respect to their lowercased equivalents.
The second list.sort
call with len
should now be self-explanatory, assuming you understand what key
does (yes, sort by length).
To understand why the first is needed before the second, consider another contrived example:
lst = ['Ronit', 'Dan', 'ram', 'dan']
First, consider just key=len
:
lst.sort(key=len)
print(lst)
['Dan', 'ram', 'dan', 'Ronit']
That "ram" looks out of place here. THIS IS PRECISELY WHY WE HAVE THE FIRST STEP. Now, adding in that step makes our output a lot more sensible.
lst.sort(key=str.lower)
lst.sort(key=len)
print(lst)
['Dan', 'dan', 'ram', 'Ronit']
So, in conclusion, the elements are ordered first case-insensitively, and then ordered by length.