Python lambda functions
Created By: chatGPT
Lambda functions in Python are small, anonymous functions that can have any number of arguments but can only have one expression. They are often used for short, throwaway functions and are defined using the
lambda
keyword. The syntax is straightforward, and they can be a convenient way to create simple functions without formally defining them using def
.add = lambda x, y: x + y
result = add(5, 3)
# result is 8
One significant use-case for lambda functions is when working with functions like
map()
, filter()
, and sorted()
. For instance, if you want to double each item in a list, using a lambda function with map()
can achieve that easily.numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
# doubled is [2, 4, 6, 8]
They can also be used to filter data, for example, extracting even numbers from a list. The
filter()
function applies the lambda function to each item in the iterable and returns only those items that evaluate to True
.def is_even(n):
return n % 2 == 0
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# even_numbers is [2, 4]
Sorting complex data structures (like a list of tuples) is another common application of lambda functions. You can define custom sort orders using lambda expressions, making your code very expressive and concise.
data = [(1, 'one'), (3, 'three'), (2, 'two')]
data_sorted = sorted(data, key=lambda x: x[0])
# data_sorted is [(1, 'one'), (2, 'two'), (3, 'three')]
While lambda functions are handy for simple tasks, it is important to remember that they are limited to a single expression. For more complex logic, using a traditional function defined with
def
is recommended.def complex_function(x):
if x < 0:
return 'Negative'
else:
return 'Positive or Zero'
result = complex_function(-5)
# result is 'Negative'