Python
Generators
Save memory using generators.
By EZ4Code Team
generatorgenerator
Code
# Generator function
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci(10):
print(num)
# Generator expression
squares = (x**2 for x in range(1000000))
print(next(squares))
# Infinite generator
def counter(start=0):
while True:
yield start
start += 1Explanation
Generators produce values on demand, saving memory when processing large data.
More Python Snippets
Sort Dictionary by Value
Sort a Python dictionary by its values in descending order.
List Comprehension
Quickly generate lists using list comprehensions.
Dictionary Merging
Multiple ways to merge dictionaries.
File Read/Write
Various ways to read and write files.
CSV Processing
Read and write CSV files using the csv module.
JSON Processing
JSON serialization and deserialization.