Chapter 4 · Objects and robust code

Iterators and generators

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 20 · Concept

for asks for the next item

By the end of this lesson, you can write functions that make values one at a time, even without end.

names = ["Ada", "Alan"]
for name in names:
    print(name)
  • A for loop calls iter(names) once. It gives an iterator: an object that hands out items one at a time.
  • Each round calls next(it) for the next item.
  • When no item is left, next raises StopIteration, and for stops quietly.
names = ["Ada", "Alan"]
it = iter(names)
print(next(it))
print(next(it))
print(next(it))
nums = [1, 2, 3]
doubled = (n * 2 for n in nums)
print(list(doubled))
print(list(doubled))
print(list(nums), list(nums))
def countdown(n):
    while n > 0:
        yield n
        n -= 1

for n in countdown(3):
    print(n)
print("Liftoff")
def evens(n):
    # yield 0, 2, 4, ... up to n
    return []

print(list(evens(10)))
print(sum(evens(6)))
import itertools

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

print(list(itertools.islice(fib(), 10)))
print(len(range(10 ** 12)))
r = range(3)
print(list(r), list(r))
# 1. squares(): yield 1, 4, 9, ... for ever
# 2. print the first five squares over 50
class Playlist:
    def __init__(self, name):
        self.name = name
        self.titles = []

    def add_title(self, title):
        self.titles.append(title)

    def __iter__(self):
        for title in self.titles:
            yield title

p = Playlist("Road trip")
p.add_title("Blue")
p.add_title("Gold")
for song in p:
    print("Playing", song)
print(list(p))
lines = ["# shopping", "eggs", "",
         "  milk  ", "# done", "bread"]
# 1. useful(lines): the lines that matter
# 2. print them numbered from 1
def walk(items):
    for x in items:
        yield x

print(list(walk([1, [2, 3], [4, [5]]])))
Terminal
Step 1 of 9Three next calls

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)