Generator Functions (1)
Generator Functions (1)
Generator Functions
Topics to be covered:
What are Lambda Functions
Working Process of Lambda Function
Lambda Functions Example
Analogy of Lambda Function
Analogy with Lambda Functions Examples
These functions allow you to iterate over a potentially large sequence of data without loading the entire
sequence into memory.
The main difference between a regular function and a generator function is that the latter uses the yield
keyword to produce a series of values over time, one at a time, rather than returning a single result.
def pw_generator():
yield 1
yield 2
yield 3
generator = pw_generator()
print(next(generator)) # Output: 1
print(next(generator)) # Output: 2
print(next(generator)) # Output: 3
Lazy Evaluation: Generator functions follow the concept of lazy evaluation. This means that the values are
generated on-the-fly and only when requested. This is particularly useful for working with large datasets or
infinite sequences.
while n > 0:
yield n
n -= 1
countdown_gen = countdown(5)
print(number)
# Output: 5, 4, 3, 2, 1
Memory Efficiency: Generators are memory-efficient because they don't store all values in memory at once.
Each value is generated and consumed one at a time, making them suitable for working with large datasets or
when memory usage is a concern.
def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib_gen = fibonacci_generator()
for _ in range(10):
print(next(fib_gen))
def pw_skills_generator():
yield "Python"
yield "Debugging"
# Usage
print(f"Learn: {skill}")
Learn: Python
Learn: Debugging
Example2:
def courses_generator():
# Usage
#output
Example3:
def data_science_concepts_generator():
# Usage
print(f"Understand: {concept}")
#output
def data_analytics_tools_generator():
yield "Pandas"
yield "NumPy"
yield "Matplotlib"
yield "SQL"
# Usage
print(f"Use: {tool}")
#output
Use: Pandas
Use: NumPy
Use: Matplotlib
Use: SQL
Example3:
def data_science_concepts_generator():
# Usage
print(f"Understand: {concept}")
#output