Python Lambda

  • Post author:
  • Post comments:0 Comments
  • Reading time:46 mins read

What is a Python lambda?

A Python lambda is a small anonymous function. It is a function that does not have a name and does not need to be defined using the def keyword.

Lambdas are used when you need a small piece of code to be executed at a later time, or when you want to pass a function as an argument to another function.

How to define a Python lambda

A Python lambda is defined using the lambda keyword, followed by a list of arguments, and a colon. The expression following the colon is the return value of the lambda. Here is the syntax:


lambda arguments: expression

For example, here is a simple lambda that takes one argument and returns the square of that argument:


square = lambda x: x**2

You can also define lambdas that take multiple arguments. For example:


sum = lambda x, y: x + y

How to use a Python lambda

You can use a Python lambda just like any other function. You can assign it to a variable, and then use that variable to call the lambda. For example:


square = lambda x: x**2

print(square(5))  # prints 25

You can also pass a lambda as an argument to another function. For example:


def apply_function(f, x):
  return f(x)


square = lambda x: x**2

print(apply_function(square, 10))  # prints 100

Examples of Python lambdas

Here are some more examples of how you can use Python lambdas:

Sorting a list using a lambda function

You can use a lambda function as the key argument in the sorted() function to sort a list. For example:


# Sort a list of tuples by the second element in each tuple

list_of_tuples = [(1, 'a'), (2, 'b'), (3, 'c')]

sorted_list = sorted(list_of_tuples, key=lambda x: x[1])

print(sorted_list)  # prints [(1, 'a'), (2, 'b'), (3, 'c')]

Filtering a list using a lambda function

You can use a lambda function as the argument in the filter() function to filter a list. For example:


# Get a list of all 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(even_numbers)  # prints [2, 4, 6, 8, 10]

Using a lambda function in a map

You can use a lambda function as the first argument in the map() function to apply a function to each element in a list. For example:


# Double each element in a list

numbers = [1, 2, 3, 4]

doubled = map(lambda x: x * 2, numbers)

print(doubled) 
Publisher
Latest posts by Publisher (see all)

Publisher

Publisher @ideasorblogs

Leave a Reply