0

I'm thinking of ways to convert a more complex function to lambda and put it inside a map instead of f. The function is this:

#this function should be in lambda
def f(s):
    if (type(s) == int):
        return s*2
    else:
        return s.replace('r', '*')

lst = [4,5,6,'rer', 'tr',50,60]
lst = list(map( f, lst))
#result of lst is [8, 10, 12, '*e*', 't*', 100, 120]
#lst = list(map ( lambda x.... , lst))

Or lambda is only supposed to deal with short functions? Big ones have to be 'decomposed' out into separate functions?

2 Answers 2

2

Use if else statement in a lambda:

print(list(map(lambda x: x*2 if type(x)==int else x.replace('r','*'),lst)))

Output:

[8, 10, 12, '*e*', 't*', 100, 120]

Even better, use isinstance:

print(list(map(lambda x: x*2 if isinstance(x,int) else x.replace('r','*'),lst)))
Sign up to request clarification or add additional context in comments.

4 Comments

perfect... is it possible to create arbitrarily long lambda functions?
@ERJAN What you mean?
how big can a lambda function be? it can be as complex and long as a separate function?
@ERJAN What makes you think there are limits to the "size" of a lambda?
1

Prefer isinstance in place of type

lst = [4,5,6,'rer', 'tr',50,60]
lst = list(map(lambda x: x*2 if isinstance(x, int) else x.replace('r', '*'), lst))

lst
[8, 10, 12, '*e*', 't*', 100, 120]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.