In this lesson we want to learn How to Iterate with Python Lambda. You can use map() function to iterate over an iterable (such as a list, tuple or set) and apply lambda function to each item.
What is Lambda in Python ?
In Python,lambda is keyword that is used to create anonymous functions. An anonymous function is a function without name which can be useful when you need to pass a small piece of code as an argument to another function, or when you want to write a short piece of code to be executed later.
A lambda function is defined using the following syntax:
lambda arguments: expression
where arguments are the inputs to the function and expression is single line of code that is executed when the function is called.
Lambda functions can be used wherever function is expected for example as an argument to the map(), filter() or reduce() functions. they can also be assigned to variable or passed as return value from another function.
For example, let’s say you have list of numbers and you want to square each number in the list:
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
[1, 4, 9, 16, 25]
Note: The map() function returns a map object, which is an iterator, so it needs to be converted to a list (or another iterable type) to be stored or printed.
This is more complex example that demonstrates the use of lambda function with other built in functions:
# a list of tuples, each representing a person's name and age
people = [("John", 32), ("Jane", 28), ("Jim", 40), ("Jerry", 35)]
# sort the list by age using a lambda function as the key
sorted_people = sorted(people, key=lambda x: x)
print("Sorted by age:", sorted_people)
# extract the names from the sorted list and convert to uppercase
names = list(map(lambda x: x.upper(), sorted_people))
print("Uppercase names:", names)
# use filter to select only people with age >= 35
selected = list(filter(lambda x: x >= 35, sorted_people))
In this example, the sorted() function is used to sort the list of people by age, where the lambda function lambda x: x is used as the key to extract the age from each tuple. The map() function is then used to extract the names from the sorted list and convert them to uppercase. Finally, the filter() function is used to select only people with age greater than or equal to 35.
Run the complete code and this will be the result.
Learn More on Python
- Python Best Libraries for Web Development
- Top 10 Python REST API Frameworks
- How to Build REST API with Flask
- Build Python REST API with FastAPI
- Python Best Frameworks for Web Development
- Why to Use Python for Web Development
- Python Top 10 Packages to Learn