Iterators and Generators

Efficient looping techniques in Python

1. What is an Iterator?

Iterator ek object hota hai jo ek time pe ek value return karta hai. Isme __iter__() aur __next__() methods hote hain.

my_list = [1, 2, 3]
it = iter(my_list)

print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3

2. Custom Iterator

Hum apna custom iterator class bana sakte hain.

class CountDown:
    def __init__(self, start):
        self.num = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.num <= 0:
            raise StopIteration
        current = self.num
        self.num -= 1
        return current

for val in CountDown(5):
    print(val)

Output:

5
4
3
2
1

3. What is a Generator?

Generator ek function hota hai jo yield ka use karta hai. Ye ek iterator return karta hai automatically.

def my_generator():
    yield 1
    yield 2
    yield 3

for val in my_generator():
    print(val)

Output:

1
2
3

4. Infinite Generators

Generators ka use infinite series generate karne ke liye bhi hota hai.

def even_numbers():
    n = 0
    while True:
        yield n
        n += 2

gen = even_numbers()

print(next(gen))  # 0
print(next(gen))  # 2
print(next(gen))  # 4

5. Generator Expressions

List comprehensions ki tarah hi generator expressions bhi hote hain.

squares = (x*x for x in range(5))
for val in squares:
    print(val)

Output:

0
1
4
9
16

Summary