Python Iterators Explained: Complete Guide with Examples









Python Iterators Explained: Complete Guide with Examples | Devyra

Understanding Python Iterators

In Python, iterators are objects that allow traversal through a sequence of values, one element at a time. They serve as a standardized mechanism to access elements without exposing the underlying structure.

What Is an Iterator?

An iterator is defined by the implementation of two essential methods: __iter__() and __next__(). These methods constitute the iterator protocol.

Iterator vs Iterable

Objects such as lists, tuples, sets, dictionaries, and strings are all iterables. This means they contain a collection of items and can return an iterator using the iter() function.

Example: Tuple Iterator

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Example: String Iterator

Strings, being sequences of characters, are also iterable:

mystr = "banana"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

Iterating Using a For Loop

Python simplifies iteration using the for loop, which implicitly creates an iterator and calls next() internally.

Example: Tuple Iteration

mytuple = ("apple", "banana", "cherry")

for x in mytuple:
  print(x)

Example: String Iteration

mystr = "banana"

for x in mystr:
  print(x)

Creating a Custom Iterator

To define a custom iterator, you need to create a class that implements both __iter__() and __next__(). Below is a simple example that returns consecutive integers starting from 1.

Example: Number Iterator

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    x = self.a
    self.a += 1
    return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

Using StopIteration to End Iteration

Without a termination condition, the iterator could run indefinitely. To control this behavior, raise a StopIteration exception once the desired limit is reached.

Example: Stop After 20 Iterations

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    if self.a <= 20:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
  print(x)

Iterators are a powerful feature in Python for sequential data access and are widely used in loops and data processing. For further learning and Python resources, explore more tutorials at Devyra.


More From Author

Python Inheritance Tutorial: Mastering OOP Concepts with Parent and Child Classes

Understanding Python Polymorphism with Practical Examples

Leave a Reply

Your email address will not be published. Required fields are marked *