The Anonymous Function You Need To Know About

The Anonymous Function You Need To Know About

Lambda functions are anonymous functions in Python. They are small, single-line functions that do not have a name and are not bound to any identifier. They are often referred to as "lambda functions" because they were introduced in the Python programming language in the late 1970s as a way to create small, anonymous functions using the lambda keyword.

One of the main advantages of using lambda functions is that they allow you to write concise, elegant code. Because they are anonymous, you do not need to spend time thinking about a good name for the function. Additionally, because they are single-line functions, you do not need to worry about formatting or indentation. This makes them a great tool for quick and dirty coding tasks, such as sorting a list of items or filtering a list of items.

Here is a simple example of how to define a lambda function in Python:

 



Example Program



add = lambda x, y: x + y
print(add(3, 4))

Output



7



In this example, we defined a lambda function called "add" that takes two arguments, "x" and "y", and returns the sum of those two arguments. We then called the function and printed the result.

Lambda functions can be used in a variety of contexts in Python. For example, you can use them as the function argument for built-in functions such as "filter" and "map".

Here is an example of using a lambda function with the "filter" function:



Example Program



numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))

Output



[2, 4, 6, 8, 10]




In this example, we defined a list of numbers and used the "filter" function to filter out only the even numbers. We used a lambda function as the first argument to the "filter" function, which takes a single argument "x" and returns "True" if "x" is even and "False" if "x" is odd.

You can also use lambda functions with the "map" function, which applies a function to each element in an iterable:



Example Program



numbers = [1, 2, 3, 4, 5]
doubled_numbers = map(lambda x: x * 2, numbers)
print(list(doubled_numbers))

Output



[2, 4, 6, 8, 10]




In this example, we defined a list of numbers and used the "map" function to double each number in the list. We used a lambda function as the first argument to the "map" function, which takes a single argument "x" and returns "x" multiplied by 2.

You can also use lambda functions with the "sorted" function to sort a list of items based on a custom sorting criteria. For example:




words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)

Output



['apple', 'date', 'banana', 'cherry']


Reference Books


Here are the books I’ve used as references for writing this article,
please feel free to read them If you don’t want your knowledge to be
limited to this article alone.