Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambdas Python for loop

Tags:

python

lambda

I wanted to use lambdas inside for loops to return if certain elements are non-numerical:

strs = ['1234', 'hello', '6787']

I can use a for loop and iterate through each element:

for elem in strs:

and check elem.islpha().

However, is there a way to use lambdas coupled with a for loop to return the word "hello"?

like image 885
Max Kim Avatar asked Jun 14 '13 02:06

Max Kim


People also ask

Can I use for loop in lambda?

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.

Can lambda have loops in Python?

You can use the lambda function in python for-loop, see below syntax.

Is lambda function faster than for loop?

Lambda functions are inline functions and thus execute comparatively faster.

Can Python lambda have multiple statements?

Lambda functions does not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function.


1 Answers

Try this, it's easy using a list comprehension:

lst =  ['1234', 'hello', '6787']
[x for x in lst if x.isalpha()]
=>  ['hello']

Or if you definitely want to use a lambda:

filter(lambda x: x.isalpha(), lst)
=>  ['hello']

Notice that you'll rarely use lambdas for filtering inside a for loop, it's not idiomatic. The way to go for filtering elements out of a list is using list comprehensions, generator expressions or (less recommended) the filter() built-in function.

like image 190
Óscar López Avatar answered Sep 27 '22 22:09

Óscar López