Skip to content

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.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.

1 thought on “Python lambda for loop | Example code”

  1. Hi Rohit,
    In the example cited above for currying, why should we write i = i ? What is the significance? I don’t see any difference between normal lambda function and this one. Please give me some explanation.

    With warm regards,
    SUNDARAVEL

Leave a Reply

Your email address will not be published. Required fields are marked *