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"
?
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.
You can use the lambda function in python for-loop, see below syntax.
Lambda functions are inline functions and thus execute comparatively faster.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With