Python lambda list | Examples code

Using lambda you can create a new list based on conditions. Python lambda can list filtering with multiple conditions. It’s also used in different functions like map(), reduce(), filter(), etc.

Example lambda list in Python

Simple example code.

Map function using lambda in python

Square the given list.

nums1 = [1, 2, 3, 4, 5]
sq = list(map(lambda a: a * a, nums1))

print(sq)

Output:

Python lambda list

Reduce function using lambda

Sum of the given list.

from functools import reduce

list2 = [1, 2, 3, 4, 5]
fins = reduce(lambda x, y: x + y, list2)
print(fins)

Output: 15

Use Lambda function inside the filter()

The filter() function in Python takes in a function and a list as arguments. Use the anonymous function to filter and comparing if divisible or not by 5.

my_list = [10, 65, 54, 99, 102, 339]

# use anonymous function
res = list(filter(lambda x: (x % 5 == 0), my_list))

print(res)

Output: [10, 65]

Lambda function in list comprehensions

res = [x * x for x in range(10)]

print(res)

Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Do comment if you have any doubts and suggestions on this Python lambda tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.