Junior
What are lambda functions in Python?
sobes.tech AI
Answer from AI
These are anonymous, small one-line functions that can have any number of arguments but only one expression. The result of the expression is returned.
They are used for simple operations where defining a full function is unnecessary, for example, as an argument to functions like map(), filter(), sorted().
# Example of using a lambda function for addition
add = lambda a, b: a + b
result = add(5, 3) # 8
# Example of using lambda with filter()
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4, 6]
# Example of using lambda with sorted()
pairs = [(1, 'b'), (2, 'a'), (3, 'c')]
sorted_pairs = sorted(pairs, key=lambda item: item[1]) # [(2, 'a'), (1, 'b'), (3, 'c')]