loop for inside lambda

Question:

I need to simplify my code as much as possible: it needs to be one line of code.
I need to put a for loop inside a lambda expression, something like that:

x = lambda x: (for i in x : print i)
Asked By: Fernando Retimo

||

Answers:

Since a for loop is a statement (as is print, in Python 2.x), you cannot include it in a lambda expression. Instead, you need to use the write method on sys.stdout along with the join method.

x = lambda x: sys.stdout.write("n".join(x) + "n")
Answered By: chepner

To add on to chepner’s answer for Python 3.0 you can alternatively do:

x = lambda x: list(map(print, x))

Of course this is only if you have the means of using Python > 3 in the future… Looks a bit cleaner in my opinion, but it also has a weird return value, but you’re probably discarding it anyway.

I’ll just leave this here for reference.

Answered By: Dair

anon and chepner’s answers are on the right track. Python 3.x has a print function and this is what you will need if you want to embed print within a function (and, a fortiori, lambdas).

However, you can get the print function very easily in python 2.x by importing from the standard library’s future module. Check it out:

>>>from __future__ import print_function
>>>
>>>iterable = ["a","b","c"]
>>>map(print, iterable)
a
b
c
[None, None, None]
>>>

I guess that looks kind of weird, so feel free to assign the return to _ if you would like to suppress [None, None, None]’s output (you are interested in the side-effects only, I assume):

>>>_ = map(print, iterable)
a
b
c
>>>
Answered By: Moradology

If you are like me just want to print a sequence within a lambda, without get the return value (list of None).

x = range(3)
from __future__ import print_function           # if not python 3
pra = lambda seq=x: map(print,seq) and None     # pra for 'print all'
pra()
pra('abc')
Answered By: qeatzy

Just in case, if someone is looking for a similar problem…

Most solutions given here are one line and are quite readable and simple. Just wanted to add one more that does not need the use of lambda(I am assuming that you are trying to use lambda just for the sake of making it a one line code).
Instead, you can use a simple list comprehension.

[print(i) for i in x]

BTW, the return values will be a list on None s.

Answered By: Vikas

We can use lambda functions in for loop
Follow below code

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

list2 = []

for i in list1:

    f = lambda i: i /2

    list2.append(f(i))
print(list2)
Answered By: Ram

First of all, it is the worst practice to write a lambda function like x = some_lambda_function. Lambda functions are fundamentally meant to be executed inline. They are not meant to be stored. Thus when you write x = some_lambda_function is equivalent to

     def some_lambda_funcion():
         pass
        

Moving to the actual answer. You can map the lambda function to an iterable so something like the following snippet will serve the purpose.

     a = map(lambda x : print(x),[1,2,3,4])
     list(a)
Answered By: Deepeshkumar

lambda is nothing but an anonymous function means no need to define a function like def name():

lambda <inputs>: <expression>
[print(x) for x in a] -- This is the for loop in one line
a = [1,2,3,4] 
l = lambda : [print(x) for x in a]
l()
output
1
2
3
4
Answered By: Nanda Thota

If you want to use the print function for the debugging purpose inside the reduce cycle, then logical or operator will help to escape the None return value in the accumulator variable.

def test_lam():
    '''printing in lambda within reduce'''
    from functools import reduce
    lam = lambda x, y: print(x,y) or x + y
    print(reduce(lam,[1,2,3]))
    
if __name__ =='__main__':
    test_lam()

Will print out the following:

1 2
3 3
6

You can make it one-liner.

Answered By: CitizenVito

Sample

myList = [1, 2, 3]
print_list = lambda list: [print(f'Item {x}') for x in list]
print_list(myList)

otherList = [11, 12, 13]
print_list(otherList)

Output

Item 1
Item 2
Item 3
Item 11
Item 12
Item 13
Answered By: Evandro
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.