Python6 min read
Python Generators
Create memory-efficient iterators using generators.
Michael Brown
December 18, 2025
0.0k0
Save memory with generators.
Basic Generator
```python def count_up_to(n): count = 1 while count <= n: yield count count += 1
for num in count_up_to(5): print(num) # 1, 2, 3, 4, 5 ```
Generator vs List
```python # List (loads all in memory) def get_squares_list(n): return [i ** 2 for i in range(n)]
Generator (one at a time) def get_squares_gen(n): for i in range(n): yield i ** 2
Memory efficient for square in get_squares_gen(1000000): print(square) ```
Generator Expression
```python # List comprehension squares_list = [i ** 2 for i in range(5)]
Generator expression (use parentheses) squares_gen = (i ** 2 for i in range(5))
print(list(squares_gen)) # [0, 1, 4, 9, 16] ```
Real-World Example
```python def read_large_file(file_path): with open(file_path) as file: for line in file: yield line.strip()
Process huge file without loading all for line in read_large_file("huge_data.txt"): process(line) ```
Remember
- yield returns one value at a time - Saves memory for large datasets - Can't access values by index
#Python#Intermediate#Generators