Search code examples
pythonstringlambdacmp

Arranging number of strings using Python's lambda function


a=['green egg','snail and lettuce','bacon','dorse naga','rutabaga ripple','cheese']
a.sort(cmp=lambda x,y:cmp(len(x),len(y)))
print a

Felt sorry for my ignorance, I don't understand how this lambda function is working, all I know about cmp is to give +1/1/0 to show the result of comparison,len gives the length of the string How did the lambda function take the arguments? in pairs? taking in 1st,2nd then 3rd,4th ? and what is the sort doing here? Thank you so much for any help!


Solution

  • Perhaps it's easier to understand using a regular function

    def cmp_function(x, y):
        return cmp(len(x), len(y))
    
    a = ['green egg','snail and lettuce','bacon','dorse naga','rutabaga ripple','cheese']
    a.sort(cmp=cmp_function)
    print a
    

    The lambda function really isn't better that the regular function here. It's harder to document and test.

    Aside: cmp is deprecated in Python2, so you should use a key function instead.

    def key_function(x):
        return len(x)
    
    a = ['green egg','snail and lettuce','bacon','dorse naga','rutabaga ripple','cheese']
    a.sort(key=key_function)
    print a
    

    As in @Roman's answer, this key_function is just a wrapper around len, so you may write

    a = ['green egg','snail and lettuce','bacon','dorse naga','rutabaga ripple','cheese']
    a.sort(key=len)
    print a
    

    As an exercise, you could add a print statement to cmp_function and key_function - see how many times each is called. Compare this with the number of items in a