Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Generating the Fibonacci Sequence

Credit: Tom Good

Problem

You need to implement a Python 2.2 generator for an infinite sequence, for example, the Fibonacci sequence.

Solution

Python 2.2’s generators provide a wonderful way to implement infinite sequences, given their intrinsically lazy-evaluation semantics:

from _ _future_ _ import generators

def fib(  ):
    "unbounded generator, creates Fibonacci sequence"
    x = 0
    y = 1
    while 1:
        x, y = y, x + y
        yield x

if _ _name_ _ == "_ _main_ _":
    g = fib(  )
    for i in range(9):
        print g.next(  ),
    print

Discussion

Python 2.2 generators let you work with infinite (unbounded) sets. As shown in this recipe, it is easy to create a generator that produces the Fibonacci sequence. Running the recipe’s script produces the following result:

c:\python22> python fib.py
1 1 2 3 5 8 13 21 34

In Python 2.2, if you start your module with the statement from _ _future_ _ import generators, yield becomes a keyword. (In 2.3 and later versions of Python, yield will always be a keyword; the “import from the future” statement lets you use it in 2.2, but only when you specifically request it.)

A generator is a function containing the keyword yield. When you call a generator, the function body does not execute. Rather, calling the generator gives you a special iterator object that wraps the function’s body, the set of its local variables (including the arguments, which are local variables that happen to be initialized by the caller), and the current point of execution, which is initially ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Python Workout

Python Workout

Reuven M. Lerner
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Catalog PageErrata