All Posts

Python Lambda Functions

Python Lambda Functions

In Python, lambda functions are a way to create small, anonymous functions (i.e., functions without a name). They are used when you need a simple function for a short period and don’t want to formally define it using def.

💡Lambda Function Syntax

The lambda function syntax is as follows:

lambda arguments: expression
  • lambda is the keyword.
  • arguments are the inputs to the function.
  • expression is what gets returned automatically.

✅ Example: Basic Lambda

add = lambda x, y: x + y
print(add(3, 5))  # Output: 8

This is equivalent to:

def add(x, y):
    return x + y

🔹 Why Use Lambda Functions?

  • Used for short tasks where a full function is not needed.
  • Often used with functions like map(), filter(), and sorted().

🔸 Examples

map() – Apply function to all elements

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x*x, nums))
print(squares)  # Output: [1, 4, 9, 16]

filter() – Filter values based on condition

nums = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)  # Output: [2, 4, 6]

sorted() – Sort by custom key

names = ['apple', 'banana', 'cherry']
sorted_names = sorted(names, key=lambda x: len(x))
print(sorted_names)  # Output: ['apple', 'banana', 'cherry']

⚠️ Limitations

  • Only one expression is allowed (no multiple statements).
  • Not suitable for complex logic.

✅ Summary Table

Feature Regular Function Lambda Function
Named Yes (def) No (anonymous)
Syntax Multi-line possible One-line only
Use Case Complex or reusable code Short, throwaway logic
Return keyword Required (return) Not required

 

Python Tutorials

Python Tutorial on this website can be found at: