41

I see it used in sorting, but what do the individual components of this line of code actually mean?

key=lambda x: x[1]

What's lambda, what is x:, why [1] in x[1] etc...

Examples

max(gs_clf.grid_scores_, key=lambda x: x[1])

sort(mylist, key=lambda x: x[1])
1
  • Ehi! That's my answer to a different question asked about 1h ago! :D
    – fog
    Apr 30, 2013 at 22:40

7 Answers 7

27

lambda effectively creates an inline function. For example, you can rewrite this example:

max(gs_clf.grid_scores_, key=lambda x: x[1])

Using a named function:

def element_1(x):
    return x[1]

max(gs_clf.grid_scores_, key=element_1)

In this case, max() will return the element in that array whose second element (x[1]) is larger than all of the other elements' second elements. Another way of phrasing it is as the function call implies: return the max element, using x[1] as the key.

19

lambda signifies an anonymous function. In this case, this function takes the single argument x and returns x[1] (i.e. the item at index 1 in x).

Now, sort(mylist, key=lambda x: x[1]) sorts mylist based on the value of key as applied to each element of the list. Similarly, max(gs_clf.grid_scores_, key=lambda x: x[1]) returns the maximum value of gs_clf.grid_scores_ with respect to whatever is returned by key for each element.

I should also point out that this particular function is already included in one of the libraries: operator. Specifically, operator.itemgetter(1) is equivalent to your key.

1
  • 1
    where is 'x' assigned a value? i mean, you sort "mylist" based upon a key, from a list produced by the lambda (inline function) but, where is the value of 'x' assigned before being passed into the lambda?
    – givonz
    Jan 1, 2020 at 21:28
17

From a reference for Python 3.7 (https://docs.python.org/3/howto/sorting.html), The key is a parameter of list.sort() and sorted(). The first built-in function modifies a list in place while the latter accepts and return iterable.

The key parameter can be defined as a function to be called on each element of list/iterable before comparison and sort, respectively. In this case, the inline function lambda x: x[1] is defined as a value of the key parameter. The lambda function takes input x return x[1] which is the second element of x.

Supposed

mylist = [[7, 8], [1, 2, 3], [2, 5, 6]]
# list(map(lambda x: x[1], mylist)) returns [8, 2 ,5]

mylistSort = sorted(mylist, key = lambda x: x[1])
# will sort the nested list based on the result of the lambda function 

Can you guess what the result? mylistSort is then [[1,2,3], [2,5,6], [7,8]] from the sorted sequence of [8,2,5] which is [2,5,8].

The max() in your example is applied to just get the max value from the outcome of the sort function.

I hope this post is helpful.

2
  • 1
    What is the meaning of x: x[1]? Oct 5, 2019 at 2:20
  • That means choosing the second item from x i.e. if x= [1,2,3] then, x[1] = 2. Since python use zero indexing, x[0] =1, x[1] =2 etc. Oct 7, 2019 at 20:18
16

One more example of usage sorted() function with key=lambda. Let's consider you have a list of tuples. In each tuple you have a brand, model and weight of the car and you want to sort this list of tuples by brand, model or weight. You can do it with lambda.

cars = [('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000), ('bmw', 'x5', 1700)]

print(sorted(cars, key=lambda car: car[0]))
print(sorted(cars, key=lambda car: car[1]))
print(sorted(cars, key=lambda car: car[2]))

Results:

[('bmw', 'x5', 1700), ('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000)]
[('lincoln', 'navigator', 2000), ('bmw', 'x5', 1700), ('citroen', 'xsara', 1100)]
[('citroen', 'xsara', 1100), ('bmw', 'x5', 1700), ('lincoln', 'navigator', 2000)]
5
distances.sort(key=lambda x: x[1])

This is the function. And here x is the list, in which we are adding x[1] i.e 2nd element of list to the sort function. So, basically we are adding every list's 2nd element (i.e x[1]) to the sort function. I hope you understand this.

2
  • What is the meaning of x: x[1]? Oct 5, 2019 at 2:20
  • f(x) = x_1, where x is an array and x_1 it's first element
    – Rayhunter
    Nov 26, 2020 at 19:30
0
viplist = [{'name': 'VIP_Collector_SSH', 'extip': '10.56.255.199', 'extport': '11004'}, {'name': 'Desktop 150 RDP', 'extip': '10.56.255.191', 'extport': '3389'}, {'name': 'BMS-HTTPS', 'extip': '10.56.255.189', 'extport': '10443'}, {'name': 'FAZ-VIP-HTTPS', 'extip': '10.56.255.180', 'extport': '10007'}]

print(sorted(viplist, key=lambda x: x['name']))
print(sorted(viplist, key=lambda x: x['extip']))
print(sorted(viplist, key=lambda x: x['extport']))

Results

[{'name': 'BMS-HTTPS', 'extip': '10.56.255.189', 'extport': '10443'}, {'name': 'Desktop 150 RDP', 'extip': '10.56.255.191', 'extport': '3389'}, {'name': 'FAZ-VIP-HTTPS', 'extip': '10.56.255.180', 'extport': '10007'}, {'name': 'VIP_Collector_SSH', 'extip': '10.56.255.199', 'extport': '11004'}]
[{'name': 'FAZ-VIP-HTTPS', 'extip': '10.56.255.180', 'extport': '10007'}, {'name': 'BMS-HTTPS', 'extip': '10.56.255.189', 'extport': '10443'}, {'name': 'Desktop 150 RDP', 'extip': '10.56.255.191', 'extport': '3389'}, {'name': 'VIP_Collector_SSH', 'extip': '10.56.255.199', 'extport': '11004'}]

[{'name': 'FAZ-VIP-HTTPS', 'extip': '10.56.255.180', 'extport': '10007'}, {'name': 'BMS-HTTPS', 'extip': '10.56.255.189', 'extport': '10443'}, {'name': 'VIP_Collector_SSH', 'extip': '10.56.255.199', 'extport': '11004'}, {'name': 'Desktop 150 RDP', 'extip': '10.56.255.191', 'extport': '3389'}]
1
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach? Nov 13, 2023 at 19:56
-2
student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),]
sorted(student_tuples, key=lambda student: student[2])   # sort by age
>>>>[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

from official documentation

2
  • 3
    This answer adds nothing to my understanding. Jan 30, 2021 at 21:23
  • student[2] means it will be sorted by the 3rd value from tuple i.e using 15,12,10
    – omkar
    Sep 16, 2021 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.