🟡 Advanced Python · Lesson 22
Iterators और Generators
Generators और Iterators क्या है?
Generators और Iterators ka matlab hai: Generators produce values one at a time using yield. They are memory efficient for large data. Simple words me, ye topic practical Python programs likhne me direct use hota hai.
Is topic ko sirf definition ke liye nahi, balki processing large files jaise real examples ke liye practice karein.
यह क्यों सीखना जरूरी है?
- Ye processing large files me kaam aata hai.
- Ye saving memory se bhi connected hai.
- Isse aap code ka output aur errors better samajh paate hain.
Important Terms
| Term | Meaning |
|---|---|
| iterator | iterator is an important term in this topic. |
| yield | Keyword that returns a value and pauses a generator. |
| next() | Function used to get the next value from an iterator. |
| lazy evaluation | lazy evaluation is an important term in this topic. |
| memory efficient | Uses less memory by producing values one by one. |
Syntax / Basic Pattern
Basic idea: pehle data तैयार करें, phir Python logic apply करें, aur finally result display करें.
Basic Pattern
def count_up_to(limit):
number = 1
while number <= limit:
yield number
number += 1
for value in count_up_to(3):
print(value)Complete Example Program
Python – generators-iterators.py
def count_up_to(limit):
number = 1
while number <= limit:
yield number
number += 1
for value in count_up_to(3):
print(value)Expected Output
1
2
3
Program Explanation
def count_up_to(limit):creates a reusable function.number = 1stores a value in number.while number <= limit:repeats the following indented statements.yield numberperforms the next step of the program logic.number += 1stores a value in number +.for value in count_up_to(3):repeats the following indented statements.print(value)displays information or calculated result on the screen.
Practical Uses
- Processing large files.
- Saving memory.
- Generating values one by one.
Common Mistakes
- Making code complex when a simple function or class is enough.
- Not handling possible errors or edge cases.
- Mixing project dependencies instead of using a virtual environment.
Practice Tasks
- Program ko
generators-iterators.pyfile me type karke run karein. - Values change karke output compare karein.
- processing large files par ek छोटा example banayen.
- Logic ko apne words me 5 lines me likhein.
सारांश
Generators and Iterators ko tab complete maanenge jab aap iska meaning, example, output aur practical use clearly explain kar saken.
💻 लाइव कोड एडिटर
इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.