Sobes.tech
Junior — Middle

Why are anonymous functions used in Python?

sobes.tech AI

Answer from AI

Anonymous functions in Python, created using the lambda keyword, are used to create small, one-line functions without the need to give them a name. This is convenient when the function is needed temporarily, for example, as an argument to other functions like map(), filter(), sorted().

Example of usage:

# Sorting a list of tuples by the second element
pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)  # [(1, 'one'), (3, 'three'), (2, 'two')]

Thus, anonymous functions allow writing compact and readable code when a full function definition is redundant.