Python For Loop Inside Lambda

[toc]

Problem: Given an iterable, how to print it using a for loop within a lambda function.

Overview

In this tutorial, we will learn why it is not a smart idea to use for loop inside Lambda in Python. This is a frequently asked question by programmers and newbies. Hence, it needs to be addressed as soon as possible.

Let us have a look at an example/question that most newbie programmers come across while dealing with the lambda function and for loops in Python. The following question is a classic example of the confusion that you might come across while using the lambda method along with a for loop.

Example:

source: stack overflow

Let’s go ahead an execute this code in our console to find out what happens!

y = "hello and welcome"
x = y[0:]
x = lambda x: (for i in x : print i)

Output:

x_list = list(lambda i: for i in x)
                            ^
SyntaxError: invalid syntax

Reason: Since a for loop is a statement, it shouldn’t be included inside a lambda expression.

✨Solution 1: Using a List Comprehension

Using a lambda function with a for loop is certainly not the way to approach problems like these. Instead, you can simply use a list comprehension to iterate over the given string/list/collection and print it accordingly, as shown in the solution below.

y = "hello and welcome"
x = y[0:].split(" ")
res = [print(i) for i in x]

Output:

hello
and
welcome

? A quick recap of list comprehensions:

List comprehension is a compact way of creating lists. The simple formula is [expression + context].
Expression: What to do with each list element?
Context: What elements to select? The context consists of an arbitrary number of for and if statements.
Example: [x for x in range(3)] creates the list [0, 1, 2].

Recommended Tutorial: List Comprehension in Python — A Helpful Illustrated Guide

✨Solution 2: Using list + map + lambda

Another workaround to our problem is to use the map() method along with a lambda function and then typecast the output to a list.

The map() function transforms one or more iterables into a new one by applying a “transformator function” to the i-th elements of each iterable. The arguments are the transformator function object and one or more iterables. If you pass n iterables as arguments, the transformator function must be an n-ary function taking n input arguments. The return value is an iterable map object of transformed, and possibly aggregated, elements.

Recommended Tutorial: Python map() — Finally Mastering the Python Map Function

Now, let’s have a look at the code/solution:

y = "hello and welcome"
x = y[0:].split(" ")
res = list(map(lambda x: print(x), x))

Output:

hello
and
welcome

✨Solution 3: Using write method on sys.stdout along with join Method

A simple solution to solve the problem is to use the write method on the sys.stdout and then use the join method on the result to display the output. Let’s have a look at the following code to understand the approach:

import sys

y = "hello and welcome"
x = y[0:].split(" ")
res = lambda x: sys.stdout.write("\n".join(x) + "\n")
res(x)

Output:

hello
and
welcome

Since conditionals are statements and so is print (in Python 2.x), they will not work inside the lambda expression. Thus, using the write method upon the sys.stdout module can help us to bypass this issue.

In case you are wondering about the difference between print and sys.stdout.write → refer to this link.

Note: The string.join(iterable) method concatenates all the string elements in the iterable (such as a list, string, or tuple) and returns the result as a new string. The string on which you call it is the delimiter string—and it separates the individual elements. For example, '-'.join(['hello', 'world']) returns the joined string 'hello-world'.

Recommended Read: Python Join List [Ultimate Guide]

?Complicated Example

The solutions to the example given above were straightforward. Now let us have a look at a slightly complicated scenario.

Problem: Given a list of numbers, store the even numbers from the list into another list and multiply each number by 5 to display the output.

The implementation of the above problem using a for loop is quite simple as shown below.

x = [2, 3, 4, 5, 6]
y = []
for v in x:
    if v % 2:
        y += [v * 5]
print(y)

Output:

[15, 25]

But, how will you solve the above problem in a single line?

The solution has already been discussed above. There are two ways of doing this:

?️Method 1: Using a List Comprehension

x = [2, 3, 4, 5, 6]
y = [v * 5 for v in x if v % 2]
print(y)

# [15, 25]

?️Method 2: Using a combination of list+map+lambda+filter

x = [2, 3, 4, 5, 6]
y = list(map(lambda v: v * 5, filter(lambda u: u % 2, x)))
print(y)

# [15, 25]

The purpose of the above example was to ensure that you are well-versed with problems that involve iterations in a single line to generate the output.

?Tidbit: When To Use Lambda Functions?

Lambda functions are utilized when you need a function for a brief timeframe. It is also used when you have to pass a function as an argument to higher-order functions (functions that accept different functions as their arguments). Let’s have a look at a couple of examples.

Example 1:

lst = [1, 2, 3, 4, 5]
# Adding 10 to every element in list using lambda
lst2 = list(map(lambda i: i + 10, lst))
# Printing the list
print("Modified List: ", lst2)

Output:

Modified List:  [11, 12, 13, 14, 15]

Example 2:

# Using lambda inside another function
def foo(no):
    return lambda i: i + no


sum = foo(10)
print("Sum:", sum(5))

Output:

Sum: 15

To learn more about the lambda function and its usage in Python, please have a look at the following tutorials:
Lambda Functions in Python: A Simple Introduction
Lambda Calculus in Python

Conclusion

Thus, the above discussion shows it is never really a great idea to use a for loop within the lambda expressions. Instead, you can use the workarounds that have been proposed above.

To keep learning, please subscribe and stay tuned for more interesting discussions and tutorials.

Recommended:  Finxter Computer Science Academy

  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.
The Complete Guide to PyCharm

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!