Skip to content

key lambda Python (Key=lambda) function example

  • by

Use key when you want to sort the data using the Python lambda function. The key lambda sorted could treat string items as an int to achieve this. This is why the key keyword argument is used.

Note: A lambda is an anonymous function:

Example Key=lambda Python

Simple example code.

Suppose the given list of items has integers and strings with numeric contents as follows,

nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]

Sort it using a sorted() function, let’s see what happens.

nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]

print(sorted(nums))

Output: TypeError: ‘<‘ not supported between instances of ‘int’ and ‘str’

Now using key

nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]

print(sorted(nums, key=int))

Output: [‘-10’, ‘-1’, 1, ‘2’, 3, 4, ‘5’, ‘8’]

Let’s use the lambda function as a value of key

names = ["annie", "Ken", "Ron", "John", "amber"]

res = sorted(names, key=lambda name: name.lower())

print(res)

Output:

key lambda Python

Source: stackoverflow.com

Another example

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

Actually, the above codes can be:

sorted(['Some','words','sort','differently'],key=str.lower)

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

Do comment if you have any doubts or suggestions on this Python lambda tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading