50

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)
8
  • 2
    Just make a function for this case! May 27, 2014 at 18:12
  • I know thats an option, as I said I need to simplify - make it one line code. May 27, 2014 at 18:13
  • 2
    Why does it need to be one line of code?
    – chepner
    May 27, 2014 at 18:16
  • 2
    I agree with you old, but that was my assignment. Regardless of what we think, this is my goal right now. May 27, 2014 at 18:22
  • 1
    The lambda functions are inline functions they are fundamentally not meant to be stored but when you write x = some lambda function, then it assigns it to the variable 'x' . So what's the use of writing a lambda function? ;) Apr 19, 2022 at 6:04

10 Answers 10

42

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

24

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")
20

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.

1
  • Slightly shorter: y = list(map(print, x))
    – Toby Sharp
    Oct 18, 2019 at 22:42
2

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

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')
1

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
1
  • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
    – user17242583
    Apr 27, 2022 at 20:14
0

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)
0

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)
0

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.

2
  • How does your response answer the OPs question?
    – Alexander
    May 1, 2022 at 10:10
  • It sure doesn't look like one line of code that has a lambda function with a for loop inside of it...
    – Alexander
    May 4, 2022 at 10:07
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.