Python Lambda Function with List Comprehension


Lambda Function with List Comprehension in Python

In Python, you can write a Lambda Function that takes a list as argument, does List Comprehension, and returns the result.

For example, the following is a lambda function that takes myList as argument, finds the square of each number in the list, and return the resulting list.

lambda numbers: [x**2 for x in numbers]

Examples

1. Find the square of the numbers in list using lambda function and list comprehension

In this example, we shall define a lambda function that takes a list of numbers myList as argument, use list compression to find the square of each number in the list, and return the resulting list.

Python Program

square_numbers = lambda numbers: [x**2 for x in numbers]

numbers = [1, 2, 3, 4, 5]
squares = square_numbers(numbers)
print(squares)

Output

[1, 4, 9, 16, 25]

2. Lambda function to return the length of strings in the list

In this example, we shall define a lambda function that takes a list of strings myList as argument, use list compression to find the length of each string in the list, and return the resulting list.

Python Program

len_of_strings = lambda names: [len(x) for x in names]

names = ['apple', 'banana', 'fig']
lengths = len_of_strings(names)
print(lengths)

Output

[5, 6, 3]

Summary

In this tutorial of Python Lambda Function, we learned how to define a lambda function that does list compression, and returns the resulting list, with the help of example programs.