python iterator code example

Example 1: python how to use iter

s = 'hello'
s_iter = iter(s) #Changes the string to an iterator
print(next(s_iter)) #Will print h
print(next(s_iter)) #Will print e
print(next(s_iter)) #Will print l
print(next(s_iter)) #Will print l
print(next(s_iter)) #will print o

Example 2: what is iteration in python

# Iteration is the execution of a statement repeatedly and without
# making any errors.

Example 3: 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 4: python iterator

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

iterator = iter(pies)

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