HELP! What's a Lambda, how do you use it and PLZ HELP! :(((


I am at home and trying to learn some coding.... and then codecademy gives me this crazy function thingy to learn!!!! I went to bed at 11:00 pm and although I won't tell you how old I am... I am under 18 and anyway... staying up that long usually makes one sleepy... and I am supposed to code for 2 hours per day. I really, really need help.



Oh.... also I don't have any code to really show. The minute i put me on my own... i hit the faq button. :sweat_smile:


A lambda is an anonymous function expression that can be assigned to a variable or performed on the fly in one-off situations. Take for instance the digit_sum problem. Using the reduce function (in Python 2),

def digit_sum(n):
    return reduce(lambda a, b: int(a) + int(b), str(n))

print digit_sum(12345)    # 15

Another example is the factorial problem...

def factorial(n):
    return reduce(lambda a, b: a * b, range(1, n + 1))

print factorial(7)    # 5040

In a problem that takes a list of numbers and computes new values from those numbers, we can use it with the map function...

def squares(n):
    return map(lambda x: x ** 2, n)

print squares([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

print tuple(squares((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)))

# (1, 4, 9, 16, 25, 36, 49, 64, 81, 100)

Another type of problem is filtering values, smaller, larger, different type, etc.

def nums_only(n):
    return filter(lambda x: isinstance(x, int) or isinstance(x, float), n)

print nums_only([1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e'])    # [1, 2, 3, 4, 5]

Read all the lesson text carefully, and re-read until it all makes sense. These advanced topics are tricky to wrap one's head around which is why they are left to the end of this track. Take some of that two hours a day and commit it to reading and studying the documentation.

The examples above only scratch the surface. There are many complex problems that can be broken down and simplified using lambda and the various iterators available in Python. You won't learn it all in one sitting, but several. Practice, study, practice, study. Then do it all again. Be sure to apply each new concept as you learn them, then review and learn new applications as you go..


THANK YOU!!! I still have to study it, but at least I will be able to eventually get it!!!!! I have 2 weeks as I dont have summer camp, so I should know lambdas by then. THANK U!!!! :gift: :grinning: :innocent: (trying to get as many happy faces as I can find)


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.