Wednesday, February 25, 2026

Python Generators and Lambda Functions

 

Python Generators and Lambda Functions

Python provides powerful features like generators and lambda functions that make code more efficient, concise, and expressive. These constructs are widely used in functional programming, data processing, and scenarios where performance and readability matter.


🌍 Generators in Python

A generator is a special type of iterator that allows you to generate values on the fly using the yield keyword. Unlike lists, generators don’t store all values in memory—they produce them one at a time, making them memory-efficient.

Example: Simple Generator

def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

for num in count_up_to(5):
    print(num)

Output:

1
2
3
4
5

Key Features of Generators

  • Lazy evaluation: Values are generated only when needed.
  • Memory efficiency: Useful for large datasets.
  • Iterator protocol: Generators implement __iter__() and __next__().

Use cases:

  • Streaming data
  • Infinite sequences
  • Pipeline processing

🛠️ Lambda Functions in Python

A lambda function is a small anonymous function defined with the lambda keyword. It can take any number of arguments but has only one expression.

Example: Lambda Function

square = lambda x: x * x
print(square(5))  # Output: 25

Common Uses of Lambda Functions

  • Inline functions: Quick one-liners without def.
  • Functional programming: Often used with map(), filter(), and reduce().
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x*x, nums))
print(squares)  # [1, 4, 9, 16, 25]
  • Sorting with custom keys:
students = [("Alice", 22), ("Bob", 19), ("Charlie", 23)]
students.sort(key=lambda s: s[1])
print(students)  # [('Bob', 19), ('Alice', 22), ('Charlie', 23)]

🔎 Generators vs. Lambda Functions

FeatureGeneratorsLambda Functions
PurposeProduce values lazilyDefine small anonymous functions
SyntaxUses yieldUses lambda keyword
MemoryEfficient, doesn’t store all valuesNo special memory optimization
Exampleyield ilambda x: x*x

📖 Conclusion

Generators provide a way to handle large or infinite sequences efficiently, while lambda functions allow concise, inline function definitions. Together, they make Python code more expressive, readable, and powerful.

No comments:

Post a Comment

Support Vector Machines in Machine Learning

Support Vector Machines in Machine Learning Introduction Support Vector Machines (SVMs) are powerful supervised learning algorithms used ...