#đź”’ lambda function
13 messages · Page 1 of 1 (latest)
@spiral blaze
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Lambdas are a way to create “anonymous” functions. That means they are functions that are not bound to a name. They are mostly used for smaller functions where defining a function the regular way would be unnecessary (maybe you need it only once or you don’t want that function in your namespace).
Consider this example
nums = [n for n in range(20)]
def is_even(x):
return x % 2 == 0
print(list(filter(is_even, nums)))
print(list(filter(lambda x: x % 2 == 0, nums)))
Functionally a lambda is the same to a regular function, but you cannot access is afterwards (if you didn’t assign it to a variable beforehand; something like is_even = lambda x: x % 2 == 0 is entirely possible).
They are never "necessary" but they are nice syntactic sugar for instances where you pass function objects to other functions (like in filter or the key argument for sorting functions)
(You can assign a variable/name to them, but that usually makes seasoned Python programmers grumpy.)
Yeah I briefly mentioned that as well, but at that point why not just use a regular function definition? 🤷‍♂️
Idk depends on a case-by-case basis I guess...
Doesn't make me grumpy. For something short it's less visually intrusive than a def, especially if an autoformatter gets and slaps blank lines above and below the def 🙂
@spiral blaze the only tight constraint on a lambda is that it must be a single expression - no control constructs like if/for/while etc.
The saying "lambdas are anonymous functions" I believe comes from lisp, where the concept of a function not having a name is remarkable.
In Python, it's more interesting to say "lambdas are function expressions", or perhaps "lambdas are function expressions that can't have more than one statement"
@spiral blaze you've gotten a lot of responses. are you still here?
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.