minte9
LearnRemember



pag. 337-338
pag. 122-124


Iterator

 
"""
    An iterator is an object implements the iterator protocol.
    An iterator is an object that contains a countable number of values.
    An interator is any object that will return objects when used in a loop context.
"""

class SquareIterator():
    def __init__(self):
        self.num = 0
    
    def __iter__(self):
        return self

    def __next__(self):
        if self.num < 5:
            res = self.num**2
            self.num += 1
            return res
        else:
            raise StopIteration

print("Iterator usage:")
squares = SquareIterator()
for n in squares:
    print(n, end=' ')
print('\n')

print("Loop through a collection:")
mydict = {'a':1, 'b': 2, 'c': 3}

for key in mydict:  # __next__() is called
    print(key, end=' ')

myiterator = iter(mydict)
print(next(myiterator), end=' ')
print(next(myiterator))

"""
    Iterator usage:
    0 1 4 9 16 

    Loop through a collection:
    a b c a b
"""

Generator

 
"""
    A generator is a simpler way to create an iterator.
    A generator is a function that yields values one at a time.
"""

def SquareGenerator(n=10):
    for i in range(1, n+1):
        yield i**2

G = SquareGenerator()
for x in G:
    print(x, end=' ')

"""
    1 4 9 16 25 36 49 64 81 100 
"""

Generator expressions

 
"""
    Generator expression is similar to list, dictionary or set comprehension.
    The expression is enclosed withing parantheses insteed of brackets.
"""

gen = (x**2 for x in range(100))

print(next(gen), end=' ')
print(next(gen), end=' ')
print(next(gen), end=' ')

# This is equivalent to the more verbose generator:

def make_gen():
    for x in range(100):
        yield x**2
gen = make_gen()

print(next(gen), end=' ')
print(next(gen), end=' ')
print(next(gen), end=' ')

"""
    0 1 4 0 1 4 
"""



  Last update: 141 days ago