Python Iterators


Iterators allow you to loop through a sequence in a controlled way. When you use a for loop in Python, you are already working with iterators in the background. Python converts the sequence into an iterator and then reads each value one by one. Understanding iterators helps you write cleaner loops and build custom objects that behave like real Python sequences.

In this tutorial, you will learn what an iterator is, how it works, how to use the iter() and next() functions, and how to create your own iterator class. You will also see real examples that show why iterators are useful in practical programs.

What Is an Iterator?

An iterator is an object that returns data one item at a time. It does not give everything at once. Instead, each value is provided only when needed. Python uses this approach to save memory and make loops more efficient.

Two things define an iterator:

  • It has an __iter__() method

  • It has a __next__() method

When you call next() on an iterator, it returns the next value. When there are no more values left, it raises a StopIteration error. This signals to Python that the loop is finished.

Using iter() and next()

The iter() function converts a sequence into an iterator. The next() function gets the next value from that iterator.

Example:

numbers = [1, 2, 3]

it = iter(numbers)

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

Output:

1
2
3

After the last value, another next(it) will raise StopIteration.

This is exactly how a for loop works internally.

How a For Loop Uses Iterators

When you write:

for n in numbers:
    print(n)

Python secretly does this:

it = iter(numbers)

while True:
    try:
        value = next(it)
        print(value)
    except StopIteration:
        break

The for loop simply hides this process and makes it easier to write.

Creating Your Own Iterator Class

You can build your own iterator by defining two methods inside a class:

  • __iter__()

  • __next__()

Example:

class Counter:
    def __init__(self, limit):
        self.limit = limit
        self.current = 1

    def __iter__(self):
        return me

    def __next__(self):
        if self.current <= self.limit:
            value = self.current
            self.current += 1
            return value
        else:
            raise StopIteration

Using the iterator:

c = Counter(5)

for n in c:
    print(n)

Output:

1
2
3
4
5

This is how you control the starting point, ending point, and stepping of the values.

Why Iterators Are Useful

Iterators are useful because they do not store all values in memory at once. They generate values only when needed. This is perfect for:

  • Large datasets

  • Long loops

  • Streams of data

  • Reading files line by line

  • Working with infinite sequences

Instead of loading everything, Python processes one item at a time.

Real Life Example: Reading a File

When you read a file using a for loop:

for line in open("data.txt"):
    print(line)

You are using an iterator. Python reads one line at a time instead of loading the entire file. This makes your program much faster and memory-friendly, especially with large files.

Creating an Iterator That Skips Values

You can also create iterators that skip numbers or add special rules.

Example:

class SkipTwo:
    def __init__(self, start, end):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= self.end:
            value = self.current
            self.current += 2
            return value
        else:
            raise StopIteration

Usage:

s = SkipTwo(1, 10)

for n in s:
    print(n)

Output:

1
3
5
7
9

This iterator jumps by 2 each time.

Infinite Iterators

You can create iterators that never end. These are used in systems where values keep coming continuously.

Example:

class Infinite:
    def __init__(self):
        self.current = 1

    def __iter__(self):
        return self

    def __next__(self):
        value = self.current
        self.current += 1
        return value

Usage:

i = Infinite()
print(next(i))
print(next(i))
print(next(i))

This keeps increasing forever.

Be careful and avoid using such iterators in for loops without break conditions.

Using Iterators With Loops

You can combine custom iterators with normal loops. For example:

c = Counter(3)

for n in c:
    print(n)

for n in c:
    print(n)

The second loop will not print anything. This is because iterators are exhausted after one complete run. You must create a new object to repeat the process.

Practical Examples

  1. Simple Iterator

it = iter([10, 20, 30])
print(next(it))
  1. Custom Counter Iterator

for n in Counter(4):
    print(n)
  1. Skipping Values

for n in SkipTwo(2, 12):
    print(n)
  1. Using Iterator in While Loop

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

while True:
    try:
        print(next(it))
    except StopIteration:
        break
  1. Iterating Over Characters

it = iter("Python")
print(next(it))
  1. Manual StopIteration

try:
    print(next(it))
except StopIteration:
    print("Finished")
  1. Using Iterator Twice

nums = [1, 2, 3]
it = iter(nums)
print(list(it))
print(list(it))
  1. Chaining Iterators

it1 = iter([1, 2])
it2 = iter([3, 4])
  1. Iterating Over a Dictionary

it = iter({"a": 1, "b": 2})
print(next(it))
  1. Reading File Line by Line

for line in open("log.txt"):
    print(line)

Summary of the Tutorial

Iterators are objects that return values one at a time. Python uses them in for loops, file reading, and many built-in operations. You can create your own iterators by defining __iter__() and __next__(). Iterators help save memory, handle large data, and let you build flexible looping systems. They are an important part of Python and are used in almost every program that processes sequences.


Practice Questions

Q1. Write a Python program to use iter() and next() to print each item from a tuple.

Q2. Write a Python program to create a list of 3 names and iterate through them using next() and iter().

Q3. Write a Python program to use a for loop to print numbers from an iterable (e.g., a range or list).

Q4. Write a Python program to build a custom iterator class that returns the squares of numbers up to 5.

Q5. Write a Python program to modify your iterator to raise StopIteration after 3 elements are returned.

Q6. Write a Python program to convert a string into an iterator and print each character one by one.

Q7. Write a Python program to create a countdown iterator that returns numbers from 5 to 1.

Q8. Write a Python program to make a custom iterator that returns only even numbers up to 10.

Q9. Write a Python program to use an iterator to read a file line by line.

Q10. Write a Python program to create an iterator that returns Fibonacci numbers up to 10.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top