for loop iterator python code example

Example 1: python defining the iterator protocol

class RangeTen:
  def __init__(self, *args): pass # optional
  
  def __iter__(self):
    '''Initialize the iterator.'''
    self.count = -1
    return self
  
  def __next__(self):
  	'''Called for each iteration. Raise StopIteration when done.'''
    if self.count < 9:
      self.count += 1
      return self.count

    raise StopIteration
    
for x in RangeTen():
  print(x) # 0, 1, ..., 9

Example 2: iterator in python

# define a list
my_list = [4, 7, 0, 3]

# get an iterator using iter()
my_iter = iter(my_list)

# iterate through it using next()

# Output: 4
print(next(my_iter))

# Output: 7
print(next(my_iter))

# next(obj) is same as obj.__next__()

# Output: 0
print(my_iter.__next__())

# Output: 3
print(my_iter.__next__())

# This will raise error, no items left
next(my_iter)

Example 3: python iterator

pies = ["cherry", "apple", "pumpkin", "pecan"]

iterator = iter(pies)

print(next(iterator))
#prints "cherry" because it's the current one being iterated over

Example 4: how to use iteration in python

n = 5
while n > 0:
    print n
    n = n-1
print 'Blastoff!'

Example 5: python for loop iterator

import numpy as np
# With array cycling
arr = np.array([1,2,3,4,5,6,7,8,9])

for i in range(len(arr)):
 # logic with iterator use (current logic replaces even numbers with zero)
    if arr[i] % 2 == 0: arr[i] = 0

print(arr)
# Output: [1, 0, 3, 0, 5, 0, 7, 0 , 9]

Tags:

Misc Example