Next

Iterators and Generators

  • Explore iterators and generators in Python to create efficient and scalable looping mechanisms.

  • Why We Use Iterators & Generators

    Iterators and generators are used to process data step-by-step instead of loading everything into memory at once.

    Main Reasons

    1. Save Memory – values are generated one by one

    2. Better Performance – faster for large data

    3. Handle Large Files – no memory overflow

    4. Clean & Simple Code – less lines of code

    5. Used in Real Applications – files, streams, logs, data pipelines

    Real-Life Examples

    Programming Concept

    Real-Life Example

    List

    Download full movie

    Iterator

    Reading a book page by page

    Generator

    Watching movie on Netflix (streaming)

    iter() – Convert Collection into Iterator

    What is iter()?

    iter() converts a collection (list, tuple, string) into an iterator.

Using iter()

This example converts a list into an iterator.

numbers = [10, 20, 30]
it = iter(numbers)
  • next() – Get Next Value

    What is next()?

    next() returns the next value from an iterator.

Using next()

This example fetches elements one by one from the iterator.

numbers = [10, 20, 30]
it = iter(numbers)

print(next(it))
print(next(it))
print(next(it))

Real-Life Example (Iterator)

Reading attendance list one student at a time

students = ["Amit", "Riya", "Neha"]
it = iter(students)

print(next(it))
print(next(it))
  • yield – Create Generator

    What is yield?

    • yield returns a value

    • Pauses the function

    • Resumes from same point

    ➡ Used to create generators

    Real-Life Example (Generator)

    ATM gives cash note by note, not all at once

Simple Generator Using yield

This generator returns numbers one by one.

def my_generator():
    yield 1
    yield 2
    yield 3

g = my_generator()
print(next(g))
print(next(g))
print(next(g))

Generator for Student Roll Numbers

This generator gives roll numbers one at a time.

def roll_numbers(n):
    for i in range(1, n + 1):
        yield i

for roll in roll_numbers(5):
    print("Roll No:", roll)
  • Iterator vs Generator

    Feature

    Iterator

    Generator

    Memory usage

    More

    Less

    Code length

    Long

    Short

    Creation

    iter()

    yield

    Performance

    Slower

    Faster

Next