1

I have just finished my code for a school project, but have used one line of code from stack overflow that is slightly more advanced than the knowledge that's in my "skill comfort zone". I do understand what it does, why it exists, etc.. But still cannot convert it into "human syntax" for my individual report. Could anyone give me a bit of their time and explain, as precisely as possible, the underlying mechanism in this line of code? Thanks in advance!

sites.sort(key = lambda x: x[0]) 

The role it has within my program is sorting a dictionary by the integers in its first column, from smallest to biggest.

Need to demonstrate that I fully understand this line of code, which I frankly do not.

Thanks!

Talenel
  • 422
  • 2
  • 6
  • 25

2 Answers2

2

A lambda function is basically like any other function, with some restrictions. It can only be one line, and it must be an expression. That expression is evaluated when the lambda function is called and the result of that expression is returned.

sites.sort(key = lambda x: x[0]) 

is the same as

def f(x):
    return x[0]
sites.sort(key = f) 

In this case, the lambda function is passed to the sort method as a key function. These are used in sorting to sort things based on something other than their value. Each element e of sites is passed to the key function, and then they are sorted based on f(e) or e[0] rather than the value of e.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
1

When calling sort on an object, Python passes each of the elements contained inside that object to the function you specify as the key parameter.

A lambda function can be dissected in the following parts:

lambda <args>: <what to do with args>

In your lambda function you have a single arg x as the <args>, and your <what to do with args> is to get the zero element of it.

That element x[0] is going to be used in the comparisons sort performs.

In your example, sites must contain elements that themselves contain elements, for example, nested lists: l = [[1, 2, 3], [0, 1, 2, 3]]. Using this example, Python is first going to pass [1, 2, 3] to the lambda as the value of x and the lambda function is going to return x[0] == 1, then it will pass [0, 1, 2, 3] to it and get back x[0] == 0. These values are used during sorting to get the ordering as you require.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • Thanks, explains it well! But I'm still missing one of the mechanisms behind it. I understand that 'sort' will take x[0] to sort the dic, but how does it "know" that it is supposed to go from the smallest to the biggest integer? Is that just the principle of 'sort'? How would you go about explaining this? – Anna Kotrba Dec 08 '16 at 18:10
  • You can say that `sort` by default sorts the elements in ascending order. You can supply an argument `reverse=True` to it if you require descending. – Dimitris Fasarakis Hilliard Dec 08 '16 at 18:13