9 2-Generators
9 2-Generators
ipynb - Colab
keyboard_arrow_down Generators
Generators are a simpler way to create iterators. They use the yield keyword to produce a series of values lazily, which means they generate
values on the fly and do not store them in memory.
def square(n):
for i in range(3):
yield i**2
square(3)
for i in square(3):
print(i)
0
1
4
a=square(3)
a
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
Cell In[10], line 1
----> 1 next(a)
StopIteration:
def my_generator():
yield 1
yield 2
yield 3
gen=my_generator()
gen
next(gen)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
Cell In[16], line 1
----> 1 next(gen)
StopIteration:
1
2
3
Generators are particularly useful for reading large files because they allow you to process one line at a time without loading the entire file into
memory.
https://colab.research.google.com/drive/159fUnxxwhjPc2NscD_nxeUhp7bSzQvJx#printMode=true 1/2
7/18/24, 10:45 AM 9.2-Generators.ipynb - Colab
### Practical : Reading LArge Files
def read_large_file(file_path):
with open(file_path,'r') as file:
for line in file:
yield line
file_path='large_file.txt'
Smt. Droupadi Murmu was sworn in as the 15th President of India on 25 July, 2022. Previously, she was the Governor of Jharkhand from 201
Born in a Santhali tribal family on 20 June, 1958 at Uparbeda village, Mayurbhanj, Odisha, Smt. Murmu’s early life was marked by hardshi
Professional Career
From 1979 to 1983, Smt. Murmu served as a Junior Assistant in the Irrigation and Power Department, Government of Odisha. Later, she serv
Public Life
In 2000, Smt. Murmu was elected from the Rairangpur constituency as a Member of the Legislative Assembly of Odisha and continued to hold
keyboard_arrow_down Conclusion
Iterators and generators are powerful tools in Python for creating and handling sequences of data efficiently. Iterators provide a way to access
elements sequentially, while generators allow you to generate items on the fly, making them particularly useful for handling large datasets and
infinite sequences. Understanding these concepts will enable you to write more efficient and memory-conscious Python programs.
https://colab.research.google.com/drive/159fUnxxwhjPc2NscD_nxeUhp7bSzQvJx#printMode=true 2/2