Sobes.tech
Junior — Middle

Can you explain what an anonymous function is in programming?

sobes.tech AI

Answer from AI

An anonymous function is a function without a name, usually created for one-time use. In Python, such functions are created using the lambda keyword.

Main features:

  • Contains a single expression, the result of which is returned automatically.
  • Used for concise function definitions, especially as arguments to other functions (e.g., map, filter, sorted).
  • Has no name, so it cannot be called by name repeatedly.

Example:

# Regular function
def add(x, y):
    return x + y

# Anonymous function (lambda)
add_lambda = lambda x, y: x + y

print(add(2, 3))        # 5
print(add_lambda(2, 3)) # 5

# Using lambda inside the map function
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16]

Anonymous functions are convenient for simple operations when you don't want to create a full-fledged named function. If the logic is complex, it's better to use a regular function.