Search code examples
pythonlambdalowercase

How does the .lower function works in lambda?


d = ['AAab', 'abc', 'Ejc','badad1']
d.sort(key=lambda s: s.lower())
print(d)

output is ['AAab', 'abc', 'badad1', 'Ejc']

I'am confused that I've called a lower function why it's returning me AAab first, then abc, then badad1 and then EJC

Shouldn't it return abc first, then badad1, then AAB, then EJC ?


Solution

  • It looks like you want str.islower:

    d.sort(key=lambda s: (not s.islower(), s))
    print(d)
    # ['abc', 'badad1', 'AAab', 'Ejc']
    

    With your current approach, you were just lowercasing all strings, so you're just getting them sorted in alphabetical order.

    Now instead you're sorting based on the result of the booleans returned by islower and the strings themselves (which seems to be what you want):

    [(not s.islower(), s) for s in d]
    # [(True, 'AAab'), (False, 'abc'), (True, 'Ejc'), (False, 'badad1')]