Lesson 38 of 4095%

(Progress persistence is disabled until Phase 9)

Python
Intermediate

Iterators and Generators

Handle massive amounts of data efficiently.

Iterators and Generators

What You’ll Learn

You’ll learn advanced iteration techniques that save memory when working with large sequences.

Iterators

An iterator is an object that contains a countable number of values and can be iterated upon. Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit)) # apple
print(next(myit)) # banana

Generators

Generators are a simple way of creating iterators. Instead of using return in a function, you use yield.

When a function uses yield, it doesn’t execute and return a single value. Instead, it returns a generator object that yields one value at a time on demand. This uses very little memory!

def count_up_to(max):
    count = 1
    while count <= max:
        yield count
        count += 1

counter = count_up_to(3)
print(next(counter)) # 1
print(next(counter)) # 2
print(next(counter)) # 3

You can loop over generators just like lists:

for num in count_up_to(5):
    print(num)

Lesson Progress

Take QuizBuild a Python Project