Python lambda for loop | Example code

You can use the lambda function in python for-loop, see below syntax.

x = lambda x: (for i in x : print i)

Python example lambda for loop

Simple example code Iterating With Python Lambdas.

list1 = [1, 2, 3, 4, 5]

list2 = []

for i in list1:
    f = lambda i: i / 2

    list2.append(f(i))
print(list2)

Output:

Python lambda for loop

How to create a lambda inside a Python loop?

Answer: Simply create a list of lambdas in a python loop using the following code.

def square(x): return lambda: x * x


lst = [square(i) for i in [1, 2, 3, 4, 5]]

for f in lst: print(f())

Output:

1
4
9
16
25

Another way: Using a functional programming construct called currying.

lst = [lambda i=i: i + i for i in range(1, 6)]
for f in lst:
    print(f())

Output:

2
4
6
8
10

Do comment if you have questions 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.