Skip to content

Lambda function in Python list

  • by

A lambda function in Python is a concise way to create small, anonymous functions. They are often used in combination with functions like map, filter, and sorted to perform quick operations on lists.

Here’s the syntax of using a lambda function in Python with lists:

map with a Lambda Function:

new_list = map(lambda argument: expression, original_list)

filter with a Lambda Function:

filtered_list = filter(lambda argument: condition, original_list)

sorted with a Lambda Function:

sorted_list = sorted(original_list, key=lambda argument: expression)

In each case, the lambda function is defined inline using the lambda keyword, followed by the arguments and the expression or condition to be applied.

Lambda function in Python list example

Here’s how you can use lambda functions with lists:

1. Using map with a Lambda Function: The map function applies a given function to all items in an input list and returns an iterator.

numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x ** 2, numbers)

result = list(squared_numbers)  # Convert the iterator to a list
print(result)

2. Using filter with a Lambda Function: The filter function applies a given function to all items in an input list and returns an iterator with the items that satisfy the function’s condition.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x: x % 2 == 0, numbers)

result = list(even_numbers)  # Convert the iterator to a list
print(result)

3. Using sorted with a Lambda Function: The sorted function can be used to sort a list based on a specific criterion defined by a lambda function.

words = ["apple", "banana", "cherry", "date", "elderberry"]
sorted_words = sorted(words, key=lambda x: len(x))

print(sorted_words)

Output:

Lambda function in Python list

Note: Lambda functions are convenient for simple operations, for more complex or reusable operations, it’s better to define regular named functions using the def keyword.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading