Skip to main content

PYTHON ITERATORS

I
TERATORS
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
apple
print(next(myit))
banana
print(next(myit))
cherry
print(type(myit))
<class 'tuple_iterator'>
The for loop actually creates an iterator object and executes the next() method for each loop.
for x in mytuple:
  print(x)
apple
banana
cherry
mystr = "banana"
for x in mystr:
  print(x)
b
a
n
a
n
a
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))
1
print(next(myiter))
2
print(next(myiter))
3
print(next(myiter))
4
print(next(myiter))
5
To prevent the iteration to go on forever, we can use the StopIteration statement.
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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Comments