Meritshot Tutorials

  1. Home
  2. »
  3. What is a Lambda Function

SQL Tutorial

Anonymous Functions (Lambda Functions)

1.1 What is a Lambda Function?

A lambda function is a small, one-line function that doesn’t need a name. It’s useful for quick,
simple operations.
* syntax lambda arguments: expression
Suppose you want to sort a list of tuples based on the second item in each tuple:

# List of tuples
data = [(1, ‘apple’), (2, ‘banana’), (3, ‘cherry’), (4, ‘date’)]
# Sort the list of tuples by the second item in each tuple using a lambda␣
↪function
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)

[(1, ‘apple’), (2, ‘banana’), (3, ‘cherry’), (4, ‘date’)]
• sorted() is used to sort the list.
• key=lambda x: x[1] specifies that the sorting should be based on the second item in each
tuple (the fruit name).
• lambda x: x[1] is a lambda function that takes a tuple x and returns the second element of
that tuple (x[1]).