How to Iterate with Python Lambda

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:

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:




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:

In this example, the sorted() function is used to sort the list of people by age, where the lambda function lambda x: x[1] 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.

How to Iterate with Python Lambda
How to Iterate with Python Lambda



Learn More on Python




Leave a Comment