<!DOCTYPE html>
Python Lambda Functions
Python lambda functions, also known as anonymous functions, are short, concise functions that can take any number of arguments but can only have one expression. They are often used in situations where you need a quick function for a short period of time or when you want to pass a function as an argument to higher-order functions.
Here is the syntax for a lambda function in Python:
lambda arguments : expression
For example, a lambda function that adds two numbers together can be written as:
add = lambda x, y: x + y
You can then call this lambda function like a regular function:
result = add(3, 5)
The result will be 8.
One of the most common use cases for lambda functions is with higher-order functions like map()
, filter()
, and reduce()
. Lambda functions can be used as arguments to these functions to apply a specific operation to each element in a list or filter out elements based on a condition.
Here is an example using the map()
function:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
The squared
list will contain [1, 4, 9, 16, 25]
.
Overall, lambda functions are a powerful tool in Python that can help you write more concise and readable code. While they should be used judiciously, they can be a handy tool in your programming toolbox.
So it's like an arrow function in JavaScript?
lambda is like decorator. They are useful tools but you are not severely crippling yourself by not using them.
Due to what I am coding for and how I write Python code, I have never saw any need or desire to use decorators. I do see personal usage for lambda, though.
Great video, but annoying music
Brilliant
This looks like a security vulnerability waiting to happen.
And this whole example can be reduced to 2 lines of code:
Nums =[3,4,5,6,7]
Cubed = [item**3 for item in Nums]
You need to keep making content
what vscode theme do u use i really like this one!
perfect video. Straight to the point and told me everything I needed to know. Thanks!
Thank you for the video!
why music in the background?
lambda vs not lambda:
def my_map(my_func, my_iter) -> list:
result = []
for item in my_iter:
new_item = my_func(item)
result.append(new_item)
return result
nums = [3, 4, 5, 6]
cube_using_lambda = my_map(lambda x: x**3, nums)
print(cube_using_lambda)
def my_func_cube(size: int) -> int:
return size**3
cube_func = my_func_cube
print(my_map(cube_func, nums))
Thank you for this! My follow up question would be wouldnt it be easier to create a for loop to cube "nums" and add it to a list called "cubed"?? I'm not seeing how using lambda was faster/easier here
Your python is looks really beautiful how can i download that
Thank you so much for this video.
You are blessed
… half-life.
you can lose lines 1-7 and just replace line 10 with: cubed = list(map(lambda x: x**3, nums))
Simple and useful tutorial❤
You're awesome
zhina
awesome vid actually, thanks