python iter() 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: iterator in python

class PowTwo:
    """Class to implement an iterator
    of powers of two"""

    def __init__(self, max=0):
        self.max = max

    def __iter__(self):
        self.n = 0
        return self

    def __next__(self):
        if self.n <= self.max:
            result = 2 ** self.n
            self.n += 1
            return result
        else:
            raise StopIteration


# create an object
numbers = PowTwo(3)

# create an iterable from the object
i = iter(numbers)

# Using next to get to the next iterator element
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))

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