Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python loop for inside lambda

In my code I need to simplify as much as possible my line of code. EDIT: I think I'm not clear enough - 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) 

I just do not know how to make it happen. Thanks!

like image 476
Fernando Retimo Avatar asked May 27 '14 18:05

Fernando Retimo


People also ask

Can we use for loop inside lambda function in Python?

Since a for loop is a statement (as is print , in Python 2. x), you cannot include it in a lambda expression.

How do you iterate through lambda in Python?

We first iterate over the list using lambda and then find the square of each number. Here map function is used to iterate over list 1. And it passes each number in a single iterate. We then save it to a list using the list function.

Is lambda function faster than for loop?

The answer is it depends. I have seen cases where using a lambda was slower and where it was faster. I have also seen that with newer updates you get more optimal code.

Is lambda faster than list comprehension?

Actually, list comprehension is much clearer and faster than filter+lambda, but you can use whichever you find easier. The first thing is the function call overhead: as soon as you use a Python function (whether created by def or lambda) it is likely that the filter will be slower than the list comprehension.


1 Answers

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.

like image 187
Vikas Avatar answered Sep 22 '22 23:09

Vikas