6. Iterators

  • Lazy evaluation,

  • Memory efficient,

  • Used in many places

    • open,

    • zip,

    • enumerate,

    • reversed

from typing import Iterable
print(issubclass(range, Iterable))
True

Hint

You can check different types in same way ex. lists, strings

from typing import Iterable, Iterator

print(isinstance(range(10), Iterable))
print(hasattr(range(10),'__iter__'))
print(callable(range(10).__iter__))
print(isinstance(iter([1,2]) , Iterator))
True
True
True
True

6.1. Iterators vs lists

# Not using too much memory - iterating on the fly
for i in ( i ** 2 for i in range(10**8)):
    print(i)
# using a lot of memory

lista = [ i ** 2 for i in range(10**8)]

Hint

Compare proces for list and generator using ps aux PID Additionally you may use linux function watch -d -n 0.1

6.2. Defining iterators

class Numbers:
    def __iter__(self):
        self.value = 1
        return self

    def __next__(self):
        value = self.value
        self.value += 1
        return value

numbers = Numbers()
my_iter = iter(numbers)

print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
1
2
3

6.3. Zip

from typing import Iterable, Iterator

za = zip([1,2,3], ['a', 'b', 'c'])
print(isinstance(za, Iterable))
print(isinstance(za, Iterator))
True
True

6.4. Exercises

  1. We got list of expenses in specific days of the week

  • expenses = [11.25, 18.0, 20.0, 10.75, 9.50]

  1. Print all numbers (without using range / len) google

  • if form like: “parking cost 1: 11.25”

Hint

You may use enumberate