user12587364
user12587364

Reputation:

Some explanation for this lambda function

Trying to get my head around how the expression below is evaluated, looking at the returned list:

sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(2-x))

which gives:

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

I'm not sure what value x in abs(2-x) takes. Is it the list elements' position [0,1,2,..,8] or the actual elements' values [1,2,3,.,9]

Can someone explain?

Upvotes: 0

Views: 75

Answers (2)

alexzander
alexzander

Reputation: 1875

x is the actual element.

when writing:

key=lambda x: abs(2-x)

its exactly such as:

def sort_key(x):
  return abs(2 - x)

but only the body of the function is passed to key when writing key=lambda x: abs(2-x).

list:

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

its sorted positions are influenced by the result of key when calling that lambda.

the actual sort:

1 -> abs(2 - 1) = (1) [position]
2 -> abs(2 - 2) = (0) [position]
3 -> abs(2 - 3) = (1) [position]
4 -> abs(2 - 4) = (2) [position]
5 -> abs(2 - 5) = (3) [position]
6 -> abs(2 - 6) = (4) [position]
7 -> abs(2 - 7) = (5) [position]
8 -> abs(2 - 8) = (6) [position]
9 -> abs(2 - 9) = (7) [position]

explanation:

  • element 1 is giving 1 so its positioned on index 1
  • element 2 is giving 0 so its positioned on index 0
  • element 3 is giving 1 so its positioned on index 1, but 1 is already occupied, so its positioned next to element on pos 1
  • element 4 is giving 2 so its positioned on index 2

....

and so on.

Upvotes: 0

norie
norie

Reputation: 9857

It's the values that are passed to the lambda and it returns the new 'keys' to be used for sorting.

In this case the lambda will return [1, 0, 1, 2, 3, 4, 5, 6, 7] so the value 2 with the key 0 will move to the front, followed by 1 and 3, which both have index 1, and then the rest of the values.

Upvotes: 1

Related Questions