1
def Sorting(lst):
    lst.sort(key=str.lower)
    lst.sort(key=len)
    return lst

lst = ["Ronit", "Dan", "Yael"]
print Sorting(lst)

This code sorts the list alphabetically then by length. I was wondering why is it "lower"? is it not going to work with upper case letters? what is it for?

cs95
  • 379,657
  • 97
  • 704
  • 746
Ariella
  • 247
  • 1
  • 3
  • 7
  • 1
    Have a look at [String comparison technique used by Python](https://stackoverflow.com/q/4806911/8944057). – eugenhu May 23 '18 at 23:51

1 Answers1

5

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Unrelated but this seems to be trying to sort the strings in shortlex order, however this relies on `sorted()` being stable, which is what is guaranteed by the manual. – eugenhu May 24 '18 at 00:00