0

Create a function get_lambda that returns a lambda function that takes a tuple and raises each element in the tuple to the second power.

>>>f = get_lambda()
>>>f((1, 2, 3, 4))
>>>(1, 4, 9, 16)

def get_lambda():
    get_lambda = lambda x: x**2
    f = get_lambda()
    f((1, 2, 3, 4))

I can't figure out why I keep getting an error. what's wrong with my code?

vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20
roadrunner
  • 45
  • 6
  • 1
    You have indentation problems and you aren't using a `return` statement. Aside from Pascal, I'm not aware of any language that sets the return value of a function by assigning to its name. – chepner Sep 25 '18 at 19:23
  • Does answers in https://stackoverflow.com/questions/6076270/python-lambda-function-in-list-comprehensions help you? – mad_ Sep 25 '18 at 19:25

1 Answers1

0

Few things to unpack here. Your get_lambda() function, as mentioned by chepner, doesn't have a return statement. Use something like this instead:

def get_lambda():
    return lambda x: x**2
f = get_lambda()

The next issue is that your lambda function takes in a number and outputs its square - it doesn't work on tuples! In order to apply it to a whole list, you can use the built-in map function, eg:

out = map(f, (1,2,3,4))
print(tuple(out)) # prints (1, 4, 9, 16)

Alternatively, you can re-write your lambda to apply to iterables (like lists and tuples):

def get_lambda():
    return lambda tup: (i**2 for i in tup)
f = get_lambda()
out = f((1,2,3,4))
print(tuple(out))
Aquarthur
  • 609
  • 5
  • 20
  • Oh sorry, I made a very elementary mistake with the missing return. Thanks for explaining in steps! I also tried running your alternative but it returns an error on the for - as "invalid syntax", why is this so? – roadrunner Sep 25 '18 at 19:36
  • I forgot some parentheses in the second solution! One second, I will edit. – Aquarthur Sep 25 '18 at 19:42