What Is Key=Lambda

What is `lambda` in Python code? How does it work with `key` arguments to `sorted`, `sum` etc.?

A lambda is an anonymous function:

>>> f = lambda: 'foo'
>>> print f()
foo

It is often used in functions such as sorted() that take a callable as a parameter (often the key keyword parameter). You could provide an existing function instead of a lambda there too, as long as it is a callable object.

Take the sorted() function as an example. It'll return the given iterable in sorted order:

>>> sorted(['Some', 'words', 'sort', 'differently'])
['Some', 'differently', 'sort', 'words']

but that sorts uppercased words before words that are lowercased. Using the key keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:

>>> def lowercased(word): return word.lower()
...
>>> lowercased('Some')
'some'
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)
['differently', 'Some', 'sort', 'words']

We had to create a separate function for that, we could not inline the def lowercased() line into the sorted() expression:

>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
File "<stdin>", line 1
sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
^
SyntaxError: invalid syntax

A lambda on the other hand, can be specified directly, inline in the sorted() expression:

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
['differently', 'Some', 'sort', 'words']

Lambdas are limited to one expression only, the result of which is the return value.

There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.

What does arr.sort(key=lambda x: (x[0],-x[1])) mean?

lambda x:(x[0],-x[1])

this generates tuples of (the first element, negative of the second element)

When you sort 2-tuples, they are sorted based on

  1. The first element
  2. If the first elements are equal, then the second element

So

arr.sort(key=lambda x:(x[0],-x[1]))

Sorts the list arr based on:

  1. the first element
  2. if the first elements are equal, then based on the negative of the second element.

(that is why [4,6] is ahead of [4,5] since -6 < -5)

Syntax behind sorted(key=lambda: ...)

key is a function that will be called to transform the collection's items before they are compared. The parameter passed to key must be something that is callable.

The use of lambda creates an anonymous function (which is callable). In the case of sorted the callable only takes one parameters. Python's lambda is pretty simple. It can only do and return one thing really.

The syntax of lambda is the word lambda followed by the list of parameter names then a single block of code. The parameter list and code block are delineated by colon. This is similar to other constructs in python as well such as while, for, if and so on. They are all statements that typically have a code block. Lambda is just another instance of a statement with a code block.

We can compare the use of lambda with that of def to create a function.

adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2

lambda just gives us a way of doing this without assigning a name. Which makes it great for using as a parameter to a function.

variable is used twice here because on the left hand of the colon it is the name of a parameter and on the right hand side it is being used in the code block to compute something.

What's the difference between key=len, key=lambda x: (len(x), x)) in python3

  • key = len sorts by length only

  • key = lambda x : (len(x), x) sorts by length first and when length is the same it sorts lexicographically

that's why the first test leaves the part 'dbca', 'bcda' as is

while the second test reorders that to 'bcda', 'dbca'

why does sort(key=lambda x: x[0]) sort by the first value in each element inside a list?

When you have a list, you sort it by comparing elements. Normally, this is straight forward. If you had a list

[1, 2, 8, 7, 3, 4]

It makes sense to just compare values by the natural ordering of the numbers. But how do I compare a list of lists by only comparing their first element? Or, what if I have a list of strings and I want to sort by the number of characters in each string so that the strings with the least number of characters come first. In this case, we want to provide a key.

The key tells python what aspect of an element is used to compare two values. So if we provide len as the key, we compare their lengths. If we provide x[0], we compare their first element. Thus the key x[0] tell's python to compare each list with one another using their first element.

In your example with the key x[0], Python would compare the two values

[1, 4], [2, 5]

by their first element, so[1, 4] < [2, 5] because 1 < 2.

Can anybody explain the Logic behind the min([1,2,3,5,6], key=lambda x: abs(x-8))

  1. abs(x-5)

    abs is absolute mathematics function which is equivalent to |x-5|.
    example : abs(x-5) when x=6 is 1, and when x=4 is also 1.

  2. lambda x: abs(x-5)

    It can be written as

    def func(x):
    return abs(x-5)

    which means for a = [1,3,4,7,8,9,12,13,14]

    lambda x: abs(x-5)

    will give

    [4, 2, 1, 2, 3, 4, 7, 8, 9]

  1. key = lambda x: abs(x-5)

    Here the value returned by this lambda function is stored in key variable.

    Thus

    key = [4, 2, 1, 2, 3, 4, 7, 8, 9]
  2. Lastly min(a, key)

    The min function uses key as an iterable to calculate minimum value.
    Using the position of minimum value obtained from key it displays the value from iterable a.

    Thus for

    key = [4(0), 2(1), 1(2), 2(3), 3(4), 4(5), 7(6), 8(7), 9(8)]

    minimum value is 1 at position 2 and it displays value at 2 position from iterable a

    [1(0), 3(1), 4(2), 7(3), 8(4), 9(5), 12(6), 13(7), 14(8)]

    which is 4.



Related Topics



Leave a reply



Submit