Sobes.tech
Junior — Middle

Explain what anonymous functions are in programming and how they are used.

sobes.tech AI

Answer from AI

Anonymous functions are functions that do not have a name and are usually created for short-term use. In Python, they are created using the lambda keyword.

They are often used when you need to pass a small function as an argument to another function, for example, for sorting, filtering, or transforming data.

Example:

# Function that squares a number
square = lambda x: x ** 2
print(square(5))  # Outputs 25

# Using lambda for sorting a list of words by length
words = ['apple', 'banana', 'cherry']
words.sort(key=lambda w: len(w))
print(words)  # ['apple', 'cherry', 'banana']

Thus, anonymous functions are convenient for concise definition of simple functions without the need to write a full definition using def.

Explain what anonymous functions are in programming… - sobes.tech