Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Lambda Functions in Python

A more concise way to create functions in Python

Mario Rodriguez
Level Up Coding
Published in
3 min readJan 23, 2023

lambda functions python
Photo by David Clode on Unsplash

Lambda functions, also known as anonymous functions, are small, one-time use functions in Python. They are defined using the lambda keyword, followed by the function's arguments and a colon, and then the expression that the function will evaluate.

Here is an example of a simple lambda function that squares its input:

square = lambda x: x**2
print(square(5)) # prints 25

In this example, lambda x: x**2 is the function definition, and square(5) is the function call. The x in the definition is the function's argument, and x**2 is the expression that gets evaluated.

Lambda functions can also take multiple arguments, separated by commas:

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

One of the main benefits of using lambda functions is that they are very concise. They are often used in situations where a small, throwaway function is needed, such as when using the map(), filter(), and reduce() built-in functions. Here's an example using the map() function to square a list of numbers:

numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers)) # prints [1, 4, 9, 16, 25]

In this case, the map() function applies the lambda x: x**2 function to each element of the numbers list.

Lambda functions can also be used in conjunction with other built-in functions such as filter() and reduce(). Here's an example using the filter() function to find even numbers in a list:

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

In this case, the filter() function applies the lambda x: x%2==0 function to each element of the numbers list and returns only the elements that evaluate to True.

Lambda functions can also be used with other libraries like sort() and sorted()

numbers = [1, 2, 3, 4, 5]
numbers.sort(key=lambda x: -x)
print(numbers) #prints [5, 4, 3, 2, 1]

Lambda functions and regular functions comparison

Written by Mario Rodriguez

Communication systems engineer | Python developer | Signal processing | AI | Machine learning | Join me in https://mario-rodriguez.medium.com/membership

No responses yet

Write a response