Iterators and iterables

Explore numbers object

numbers = [1,2,3,4]
print(dir(numbers))
value = iter(numbers)

item1 = value.__next__()
print(item1)

item2 = next(value)
print(item2)

Iterator objects

When running a for loop python builds an iterator behind the scenes as using a while loop as shown in the next code cell. Iterators are simply objects that implement the iter() method and the next() method.

num_list = [1,4,9]
iter_obj = iter(num_list) # builds an iterator object from an object

while(True):
    try:
        element = next(iter_obj)
        print(element)
    except StopIteration:
        break

Generators

Generators allows to create iterators in an easier way. lets implement the code creating a custom iterator. Then less use the generator function to create the same iterator. (Generators are much simpler and they handle implcitly many things you do when implementing a custom iterator,not using the generator function)

Implementing a fibonacci generator

def generate_fibonacci(sequence_number):
    result = []
    count = 0
    def generate_number():
        n1 = 0
        n2 = 1
        while True:
            result.append(n1)
            n1, n2 = n2, n1 + n2
            count += 1

    while count <= sequence_number:
        generate_number()

print(generate_fibonacci(5))