Python Iterators

An Iterator is an object that allows you to traverse through all the elements of a collection one at a time. In Python, iterators implement two methods: Create an Iterator Use the iter() function to create an iterator from an iterable. Example Output: Using next() The next() function returns the next item from an iterator. […]

2 mins read Lesson 25 of 56 45% through track

An Iterator is an object that allows you to traverse through all the elements of a collection one at a time.

In Python, iterators implement two methods:

  • __iter__()
  • __next__()

Create an Iterator

Use the iter() function to create an iterator from an iterable.

Example

fruits = ["apple", "banana", "mango"]

iterator = iter(fruits)

print(next(iterator))
print(next(iterator))
print(next(iterator))

Output:

apple
banana
mango

Using next()

The next() function returns the next item from an iterator.

Example

numbers = [10, 20, 30]

iterator = iter(numbers)

print(next(iterator))

Output:

10

Iterator in a Loop

The for loop automatically uses an iterator.

Example

fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
mango

StopIteration Exception

When there are no more items, Python raises a StopIteration exception.

Example

numbers = [1, 2]

iterator = iter(numbers)

print(next(iterator))
print(next(iterator))
print(next(iterator))

Output:

1
2
StopIteration

Creating a Custom Iterator

Example

class Numbers:
    def __iter__(self):
        self.num = 1
        return self

    def __next__(self):
        if self.num <= 5:
            value = self.num
            self.num += 1
            return value
        raise StopIteration

numbers = Numbers()

for number in numbers:
    print(number)

Output:

1
2
3
4
5

Infinite Iterator

Example

class Infinite:
    def __iter__(self):
        self.num = 1
        return self

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

iterator = iter(Infinite())

print(next(iterator))
print(next(iterator))
print(next(iterator))

Output:

1
2
3

Why Use Iterators?

  • Efficient memory usage.
  • Process large datasets one item at a time.
  • Useful for custom data traversal.
  • Forms the foundation of generators.

Summary

  • Iterators allow sequential access to collection items.
  • iter() creates an iterator.
  • next() returns the next item.
  • StopIteration is raised when items are exhausted.
  • Custom iterators can be created using __iter__() and __next__().
  • Iterators help process data efficiently.