Facebook PixelPython Iterators | Python Tutorial | CodeWithHarry

Python Iterators

Iterators in Python are used to iterate over iterable objects or container datatypes like lists, tuples, dictionaries, sets, etc.

It consists of __iter__() and __next__() methods.

__iter__(): To initialize an iterator, use the __iter__() method.

__next__(): This method returns the next item of the sequence.

Using inbuilt iterators:

string = 'Hello World'
iterObj = iter(string)
 
while True:
    try:
        char1 = next(iterObj)
        print(char1)
    except StopIteration:
        break

Output:

H
e
l
l
o

W
o
r
l
d

Creating Custom iterators:

class multipleOf4:
  def __iter__(self):
    self.count = 0
    return self
 
  def __next__(self):
    if self.count <= 24:
      x = self.count
      self.count += 4
      return x
    else:
      raise StopIteration
 
obj1 = multipleOf4()
number = iter(obj1)
 
for x in number:
  print(x)

Output:

0
4
8
12
16
20
24

In both the above examples, we can see that there is a StopIteration statement inside the except block. This is to prevent the iteration from continuing forever.