Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this example of a lambda function work? [closed]

Tags:

python

lambda

I’m learning about lambdas in Python, but I don’t understand what’s going on in this example.

Can anyone explain what's going on here in plain English? The example says it's “passing a small function as an argument”, but I don’t understand what that means.

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
like image 969
SpicyClubSauce Avatar asked Apr 21 '15 19:04

SpicyClubSauce


People also ask

Is a lambda function a closure?

Lambda functions may be implemented as closures, but they are not closures themselves. This really depends on the context in which you use your application and the environment. When you are creating a lambda function that uses non-local variables, it must be implemented as a closure.

Why a lambda expression forms a closure?

a function that can be treated as an object is just a delegate. What makes a lambda a closure is that it captures its outer variables. lambda expressions converted to expression trees also have closure semantics, interestingly enough.

What is a lambda function explain with example?

Creating a Lambda FunctionThe lambda operator cannot have any statements and it returns a function object that we can assign to any variable. For example: remainder = lambda num: num % 2 print(remainder(5)) Output 1. In this code the lambda num: num % 2 is the lambda function.

How does lambda function works?

You organize your code into Lambda functions. Lambda runs your function only when needed and scales automatically, from a few requests per day to thousands per second. You pay only for the compute time that you consume—there is no charge when your code is not running.


1 Answers

You're using a lambda expression (or anonymous function), to sort your list of tuples based on a certain key. pair[1] indicates that you are sorting with a key of the elements in the index position of 1 in each tuple (the strings). Sorting with strings sorts by alphabetical order, which results in the output you are seeing.

Were you to use the first element in each tuple as the sorting key for instance (pair[0]), you would then sort in increasing numerical order:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[0])
>>> pairs
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
like image 128
miradulo Avatar answered Sep 21 '22 20:09

miradulo