0

Okay, So I've been seeing a TON of Lambda functions in Python code. I keep looking at previously asked questions about Lambdas, but they don't explain what they DO. Do they set a variable? For example, if I did Lambda x: x + 1, would it set the variable X to equal x+1? Also, How do you print the value of a Lambda? Thanks

Ryan Ding
  • 43
  • 4
  • 1
    A lambda is just a function. It does whatever the function body tells it to do. `x: x + 1` will take one parameter and return the result of adding one to the passed in argument. Presumably `x` is expected to be a number. Should be equivalent to `def foo(x): return x + 1`. – VLAZ Dec 11 '20 at 15:47
  • @deceze: also potential duplicate: https://stackoverflow.com/questions/13669252/what-is-key-lambda . (edited) it has more votes, so I floagged your duplicate target as a duplicate of the above. – Pac0 Dec 11 '20 at 15:48
  • They're essentially shorthand for a single function which evaluates and returns exactly one expression. Nothing more, nothing less. They don't need to be named like traditional `def`s and can simply be declared inline wherever a function object is needed. – deceze Dec 11 '20 at 15:50

2 Answers2

0

Lambda are anonymous functions.

MetallimaX
  • 594
  • 4
  • 13
0

In your example lambda x: x+1 will take an argument x and return x+1, equivalent to def foo(x): return x+1, these are also called anonymous functions.

Lambdas are extremely useful while passing a function as an argument. Let's give you an example. Suppose you have a 2D list of tuples:

l = [('a',2),('b',3),('c',1)]

And you want to sort the list using the second item in each tuple. Manually it will take a lot of code to do this manually, but with lambdas you can pass a lambda function as a key to sort method or sorted() like this:

l.sort(key=lambda x: x[1])

And there are more examples!!!

Wasif
  • 14,755
  • 3
  • 14
  • 34