Pythonistas, welcome back! Today we’ll look at a special type of Python function called a ‘lambda’. Lambda functions, also known as anonymous functions, are short, inline functions that can be defined in a single line of code. Because of their simplicity and conciseness, they are a useful tool in your Python toolset. A lambda function has the following syntax:
lambda arguments: expression
The keyword ‘lambda’ is followed by one or more arguments, a colon, and an expression. This function can be used in any situation where function objects are required. For example, suppose we want a function that adds two numbers. Here’s how you’d do it with ‘lambda’:
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
In this example, **x**
and **y**
are the arguments, and **x + y**
is the expression that gets evaluated and returned. Lambda functions shine when used in combination with functions like **map()**
, **filter()
,** and **reduce()
,** which we learned in the previous module. #### ExerciseIt’s your turn now! Write a Python program that uses a lambda function to:- Create a list of numbers from 1 to 10.
- Use a lambda function with
**filter()**
to select even numbers from the list. - Use a lambda function with
**map()**
to square the selected numbers.
Conclusion
Excellent effort, Pythonistas! You now have lambda functions in your Python toolbox. These little functions are incredibly versatile, and they can make your code clearer and more efficient. So, keep experimenting and practicing with them. Onward and upward on your Python journey!