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.
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.
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")
Issue with creating lambda functions using for loop
What is the purpose of Lambda expressions?
Lambda vs For each loops
How do I replace loops (nested loops) with a combination of lambda function, map, reduce, and filter in Python?
Hey all,
Can someone explain why when I run the below code:
arr = []
for n in range(1,5):
arr.append(lambda n: 5+n)
I can't run one of the functions in the array by simply calling arr[0]()with empty parenthesis?
it throws an error saying I need to pass one positional argument, n - but I'm passing it using for loop, am I not?
There is evidently something I'm missing.
What makes it worse to me is that ok, if I pass an argument, say I will call art[0](7) - that makes the n in my lambda and in for loop useless, because the value (of n) didn't get passed at all to that lambda n: definition...
Any help would be appreciated!