0

I have a variables that I am trying to turn into a lambda function but I am struggling to get the input variable to work in the lambda expression.

My variables are:

function_name = 'add'
inpt = 'a,b,c'

and I want the output to be abc * 5 (a,b,c,a,b,c,a,b,c). However it is important that I use the variables rather than simply typing this.

I have tried to use a dictionary as such:

my_dict = {}
my_dict[function_name] =lambda inpt: inpt*5

However the output is a lambda function and I still have to manually enter the value of inpt instead of it taking the variable.

I am fairly new to programming so I may have misunderstood how the lambda function works. Any help would be appreciated.

4
  • HI geds, Can you post your whole lambda function (I guess you are talking about aws lambda)? Commented Dec 1, 2019 at 23:15
  • Show how you want to use the function. You want to supply the data when the function is created instead of called? Commented Dec 1, 2019 at 23:18
  • Are you looking for the following a lambda like this lambda: inpt*5? It almost seems like you do not even need to give it a parameter. Commented Dec 1, 2019 at 23:29
  • my_dict[function_name](inpt) Commented Dec 1, 2019 at 23:36

2 Answers 2

1

Just don't give the lambda a parameter:

function_name = 'add'
inpt = 'a,b,c'

my_dict = {}
my_dict[function_name] = lambda: inpt * 5  # Don't say that the lambda takes a inpt argument

>>> my_dict[function_name]()  # Now we don't need to supply that here
'a,b,ca,b,ca,b,ca,b,ca,b,c'

I'll note that the output isn't technically correct, but that's not the main point here. You could try using ", ".join on a list of ['a', 'b', 'c'] after using list multiplication to get a better result.

Sign up to request clarification or add additional context in comments.

7 Comments

Brilliant thanks, this is what I needed. One other thing, is there anyway that I am able to print this function in a single line as well e.g. add = lambda: a,b,c * 5
@geds133 What do you mean "print this function"? print(my_dict[function_name]())?
So I recieve the output there a,b,ca,b,ca,b,ca,b,ca,b,c, whereas I want to able to print a string in the format add = lambda: a,b,c * 5
@geds133 You want to print out the literal source code?
@geds133 getsource, although you probably shouldn't need to use that beyond debugging and a few other corner scenarios.
|
0
inpt = 'a,b,c'
func = lambda inpt: ''.join(inpt.split(','))
d = tuple(func(inpt*5))

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.