Sobes.tech
Junior — Middle

Can you describe the main features and advantages of using lambda functions?

sobes.tech AI

Answer from AI

Lambda functions in Python are anonymous functions defined using the lambda keyword. They allow creating small functions in a single line, which is convenient for brief operations.

Main features and advantages:

  • Conciseness: enable writing functions without explicit def declaration.
  • Use as arguments: often used to pass functions to other functions (e.g., in map, filter, sorted).
  • Convenience for simple operations: suitable for simple expressions where multi-line code is not required.

Example:

# 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')]

However, for complex logic, it is better to use regular functions with def.