Complete Assigned Readings

Open a section to study the full text and its source attribution. Course links open the assigned section directly.

csv — CSV file reading and writing

Assigned source reading · Python Software Foundation and Python documentation contributors

Copyright © 2001 Python Software Foundation; All Rights Reserved

Original source · Python Software Foundation License Version 2 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Full license and notices
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
¶
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
   the Individual or Organization ("Licensee") accessing and otherwise using this
   software ("Python") in source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., "Copyright © 2001 Python Software Foundation; All Rights
   Reserved" are retained in Python alone or in any derivative version
   prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python or any part thereof, and wants to make the
   derivative work available to others as provided herein, then Licensee hereby
   agrees to include in any such work a brief summary of the changes made to Python.

4. PSF is making Python available to Licensee on an "AS IS" basis.
   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship
   of agency, partnership, or joint venture between PSF and Licensee.  This License
   Agreement does not grant permission to use PSF trademarks or trade name in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.

8. By copying, installing or otherwise using Python, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.

csv — CSV file reading and writing

Source code: Lib/csv.py


The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180. The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.

The csv module implements classes to read and write tabular data in CSV format. It allows programmers to say, “write this data in the format preferred by Excel,” or “read data from this file which was generated by Excel,” without knowing the precise details of the CSV format used by Excel. Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats.

The csv module’s reader and writer objects read and write sequences. Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.

See also

PEP 305 - CSV File API

The Python Enhancement Proposal which proposed this addition to Python.

Module contents

The csv module defines the following functions:

csv.reader(csvfile, /, dialect='excel', **fmtparams)

Return a reader object that will process lines from the given csvfile. A csvfile must be an iterable of strings, each in the reader’s defined csv format. A csvfile is most commonly a file-like object or list. If csvfile is a file object, it should be opened with newline=''. [1] An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of the Dialect class or one of the strings returned by the list_dialects() function. The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect. For full details about the dialect and formatting parameters, see section Dialects and formatting parameters.

Each row read from the csv file is returned as a list of strings. No automatic data type conversion is performed unless the QUOTE_NONNUMERIC format option is specified (in which case unquoted fields are transformed into floats).

A short usage example:

>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

where eggs.csv contains:

Spam Spam Spam Spam Spam |Baked Beans|
Spam |Lovely Spam| |Wonderful Spam|
csv.writer(csvfile, /, dialect='excel', **fmtparams)

Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a write() method. If csvfile is a file object, it should be opened with newline='' [1]. An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of the Dialect class or one of the strings returned by the list_dialects() function. The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect. For full details about dialects and formatting parameters, see the Dialects and formatting parameters section. To make it as easy as possible to interface with modules which implement the DB API, the value None is written as the empty string. While this isn’t a reversible transformation, it makes it easier to dump SQL NULL data values to CSV files without preprocessing the data returned from a cursor.fetch* call. All other non-string data are stringified with str() before being written.

A short usage example:

import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

which writes eggs.csv containing:

Spam Spam Spam Spam Spam |Baked Beans|
Spam |Lovely Spam| |Wonderful Spam|
csv.register_dialect(name, /, dialect='excel', **fmtparams)

Associate dialect with name. name must be a string. The dialect can be specified either by passing a sub-class of Dialect, or by fmtparams keyword arguments, or both, with keyword arguments overriding parameters of the dialect. For full details about dialects and formatting parameters, see section Dialects and formatting parameters.

csv.unregister_dialect(name)

Delete the dialect associated with name from the dialect registry. An Error is raised if name is not a registered dialect name.

csv.get_dialect(name)

Return the dialect associated with name. An Error is raised if name is not a registered dialect name. This function returns an immutable Dialect.

csv.list_dialects()

Return the names of all registered dialects.

csv.field_size_limit()
csv.field_size_limit(new_limit)

Returns the current maximum field size allowed by the parser. If new_limit is given, this becomes the new limit.

The csv module defines the following classes:

class csv.DictReader(f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)

Create an object that operates like a regular reader but maps the information in each row to a dict whose keys are given by the optional fieldnames parameter.

The fieldnames parameter is a sequence. If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames and will be omitted from the results. If fieldnames is provided, they will be used and the first row will be included in the results. Regardless of how the fieldnames are determined, the dictionary preserves their original ordering.

If a row has more fields than fieldnames, the remaining data is put in a list and stored with the fieldname specified by restkey (which defaults to None). If a non-blank row has fewer fields than fieldnames, the missing values are filled-in with the value of restval (which defaults to None).

All other optional or keyword arguments are passed to the underlying reader instance.

If the argument passed to fieldnames is an iterator, it will be coerced to a list.

Changed in version 3.6: Returned rows are now of type OrderedDict.

Changed in version 3.8: Returned rows are now of type dict.

A short usage example:

>>> import csv
>>> with open('names.csv', newline='') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         print(row['first_name'], row['last_name'])
...
Eric Idle
John Cleese

>>> print(row)
{'first_name': 'John', 'last_name': 'Cleese'}

where names.csv contains:

first_name,last_name
Eric,Idle
John,Cleese
class csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)

Create an object which operates like a regular writer but maps dictionaries onto output rows. The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to file f. The optional restval parameter specifies the value to be written if the dictionary is missing a key in fieldnames. If the dictionary passed to the writerow() method contains a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to 'raise', the default value, a ValueError is raised. If it is set to 'ignore', extra values in the dictionary are ignored. Any other optional or keyword arguments are passed to the underlying writer instance.

Note that unlike the DictReader class, the fieldnames parameter of the DictWriter class is not optional.

If the argument passed to fieldnames is an iterator, it will be coerced to a list.

A short usage example:

import csv

with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

which writes names.csv containing:

first_name,last_name
Baked,Beans
Lovely,Spam
Wonderful,Spam
class csv.Dialect

The Dialect class is a container class whose attributes contain information for how to handle doublequotes, whitespace, delimiters, etc. Due to the lack of a strict CSV specification, different applications produce subtly different CSV data. Dialect instances define how reader and writer instances behave.

All available Dialect names are returned by list_dialects(), and they can be registered with specific reader and writer classes through their initializer (__init__) functions like this:

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
class csv.excel

The excel class defines the usual properties of an Excel-generated CSV file. It is registered with the dialect name 'excel'.

class csv.excel_tab

The excel_tab class defines the usual properties of an Excel-generated TAB-delimited file. It is registered with the dialect name 'excel-tab'.

class csv.unix_dialect

The unix_dialect class defines the usual properties of a CSV file generated on UNIX systems, i.e. using '\n' as line terminator and quoting all fields. It is registered with the dialect name 'unix'.

Added in version 3.2.

class csv.Sniffer

The Sniffer class is used to deduce the format of a CSV file.

The Sniffer class provides two methods:

sniff(sample, delimiters=None)

Analyze the given sample and return a Dialect subclass reflecting the parameters found. If the optional delimiters parameter is given, it is interpreted as a string containing possible valid delimiter characters.

If several delimiters fit the sample equally well — for example if both ',' and ';' split every row consistently — the delimiters listed in the preferred attribute are preferred, in that order, no matter how many times each of them occurs.

has_header(sample)

Analyze the sample text (presumed to be in CSV format) and return True if the first row appears to be a series of column headers. Inspecting each column, one of two key criteria will be considered to estimate if the sample contains a header:

  • the second through n-th rows contain numeric values

  • the second through n-th rows contain strings where at least one value’s length differs from that of the putative header of that column.

Twenty-one rows after the header are sampled; if more than half of the columns + rows meet the criteria, True is returned.

Note

This method is a rough heuristic and may produce both false positives and negatives.

The Sniffer class has the following attribute:

preferred

The list of the delimiters preferred for breaking ties, in the order of preference. It can be modified. Its initial value is [',', '\t', ';', ' ', ':'].

An example for Sniffer use:

with open('example.csv', newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    reader = csv.reader(csvfile, dialect)
    # ... process CSV file contents here ...

The csv module defines the following constants:

csv.QUOTE_ALL

Instructs writer objects to quote all fields.

csv.QUOTE_MINIMAL

Instructs writer objects to only quote those fields which contain special characters such as delimiter, quotechar, '\r', '\n' or any of the characters in lineterminator. If doublequote is False and escapechar is set, the quotechar is escaped instead of causing the field to be quoted.

csv.QUOTE_NONNUMERIC

Instructs writer objects to quote all non-numeric fields.

Instructs reader objects to convert all non-quoted fields to type float.

Note

Some numeric types, such as bool, Fraction, or IntEnum, have a string representation that cannot be converted to float. They cannot be read in the QUOTE_NONNUMERIC and QUOTE_STRINGS modes.

csv.QUOTE_NONE

Instructs writer objects to never quote fields. When the current delimiter, quotechar, escapechar, '\r', '\n' or any of the characters in lineterminator occurs in output data it is preceded by the current escapechar character. If escapechar is not set, the writer will raise Error if any characters that require escaping are encountered. Set quotechar to None to prevent its escaping.

Instructs reader objects to perform no special processing of quote characters.

csv.QUOTE_NOTNULL

Instructs writer objects to quote all fields which are not None. This is similar to QUOTE_ALL, except that if a field value is None an empty (unquoted) string is written.

Instructs reader objects to interpret an empty (unquoted) field as None and to otherwise behave as QUOTE_ALL.

Added in version 3.12.

csv.QUOTE_STRINGS

Instructs writer objects to always place quotes around fields which are strings. This is similar to QUOTE_NONNUMERIC, except that if a field value is None an empty (unquoted) string is written.

Instructs reader objects to interpret an empty (unquoted) string as None and to otherwise behave as QUOTE_NONNUMERIC.

Added in version 3.12.

The csv module defines the following exception:

exception csv.Error

Raised by any of the functions when an error is detected.

Dialects and formatting parameters

To make it easier to specify the format of input and output records, specific formatting parameters are grouped together into dialects. A dialect is a subclass of the Dialect class containing various attributes describing the format of the CSV file. When creating reader or writer objects, the programmer can specify a string or a subclass of the Dialect class as the dialect parameter. In addition to, or instead of, the dialect parameter, the programmer can also specify individual formatting parameters, which have the same names as the attributes defined below for the Dialect class.

Dialects support the following attributes:

Dialect.delimiter

A one-character string used to separate fields. It defaults to ','.

Dialect.doublequote

Controls how instances of quotechar appearing inside a field should themselves be quoted. When True, the character is doubled. When False, the escapechar is used as a prefix to the quotechar. It defaults to True.

On output, if doublequote is False and no escapechar is set, Error is raised if a quotechar is found in a field.

Dialect.escapechar

A one-character string used by the writer to escape characters that require escaping:

  • the delimiter, the quotechar, '\r', '\n' and any of the characters in lineterminator are escaped if quoting is set to QUOTE_NONE;

  • the quotechar is escaped if doublequote is False;

  • the escapechar itself.

On reading, the escapechar removes any special meaning from the following character. It defaults to None, which disables escaping.

Changed in version 3.10: Previously the escapechar itself was not escaped, which lost it on reading.

Changed in version 3.11: An empty escapechar is not allowed.

Dialect.lineterminator

The string used to terminate lines produced by the writer. It defaults to '\r\n'.

Note

The reader is hard-coded to recognise either '\r' or '\n' as end-of-line, and ignores lineterminator. This behavior may change in the future.

Dialect.quotechar

A one-character string used to quote fields containing special characters, such as the delimiter or the quotechar, or which contain new-line characters ('\r', '\n' or any of the characters in lineterminator). It defaults to '"'. Can be set to None to prevent escaping '"' if quoting is set to QUOTE_NONE.

Changed in version 3.11: An empty quotechar is not allowed.

Dialect.quoting

Controls when quotes should be generated by the writer and recognised by the reader. It can take on any of the QUOTE_* constants and defaults to QUOTE_MINIMAL if quotechar is not None, and QUOTE_NONE otherwise.

Dialect.skipinitialspace

When True, spaces immediately following the delimiter are ignored. The default is False. When combining delimiter=' ' with skipinitialspace=True, unquoted empty fields are not allowed.

Dialect.strict

When True, raise exception Error on bad CSV input. The default is False.

Reader objects

Reader objects (DictReader instances and objects returned by the reader() function) have the following public methods:

csvreader.__next__()

Return the next row of the reader’s iterable object as a list (if the object was returned from reader()) or a dict (if it is a DictReader instance), parsed according to the current Dialect. Usually you should call this as next(reader).

Reader objects have the following public attributes:

csvreader.dialect

A read-only description of the dialect in use by the parser.

csvreader.line_num

The number of lines read from the source iterator. This is not the same as the number of records returned, as records can span multiple lines.

DictReader objects have the following public attribute:

DictReader.fieldnames

If not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file.

Writer objects

writer objects (DictWriter instances and objects returned by the writer() function) have the following public methods. A row must be an iterable of strings or numbers for writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects. Note that complex numbers are written out surrounded by parens. This may cause some problems for other programs which read CSV files (assuming they support complex numbers at all).

csvwriter.writerow(row, /)

Write the row parameter to the writer’s file object, formatted according to the current Dialect. Return the return value of the call to the write method of the underlying file object.

Changed in version 3.5: Added support of arbitrary iterables.

csvwriter.writerows(rows, /)

Write all elements in rows (an iterable of row objects as described above) to the writer’s file object, formatted according to the current dialect.

Writer objects have the following public attribute:

csvwriter.dialect

A read-only description of the dialect in use by the writer.

DictWriter objects have the following public method:

DictWriter.writeheader()

Write a row with the field names (as specified in the constructor) to the writer’s file object, formatted according to the current dialect. Return the return value of the csvwriter.writerow() call used internally.

Added in version 3.2.

Changed in version 3.8: writeheader() now also returns the value returned by the csvwriter.writerow() method it uses internally.

Examples

The simplest example of reading a CSV file:

import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

Reading a file with an alternate format:

import csv
with open('passwd', newline='') as f:
    reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
    for row in reader:
        print(row)

The corresponding simplest possible writing example is:

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

Since open() is used to open a CSV file for reading, the file will by default be decoded into Unicode using UTF-8. To decode a file using a different encoding, use the encoding argument of open:

import csv
with open('some.csv', newline='', encoding='latin-1') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

The same applies to writing in something other than the default encoding: specify the encoding argument when opening the output file.

Registering a new dialect:

import csv
csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
with open('passwd', newline='') as f:
    reader = csv.reader(f, 'unixpwd')

A slightly more advanced use of the reader — catching and reporting errors:

import csv, sys
filename = 'some.csv'
with open(filename, newline='') as f:
    reader = csv.reader(f)
    try:
        for row in reader:
            print(row)
    except csv.Error as e:
        sys.exit(f'file {filename}, line {reader.line_num}: {e}')

And while the module doesn’t directly support parsing strings, it can easily be done:

import csv
for row in csv.reader(['one,two,three']):
    print(row)

Footnotes

doctest — Test interactive Python examples

Assigned source reading · Python Software Foundation and Python documentation contributors

Copyright © 2001 Python Software Foundation; All Rights Reserved

Original source · Python Software Foundation License Version 2 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Full license and notices
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
¶
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
   the Individual or Organization ("Licensee") accessing and otherwise using this
   software ("Python") in source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., "Copyright © 2001 Python Software Foundation; All Rights
   Reserved" are retained in Python alone or in any derivative version
   prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python or any part thereof, and wants to make the
   derivative work available to others as provided herein, then Licensee hereby
   agrees to include in any such work a brief summary of the changes made to Python.

4. PSF is making Python available to Licensee on an "AS IS" basis.
   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship
   of agency, partnership, or joint venture between PSF and Licensee.  This License
   Agreement does not grant permission to use PSF trademarks or trade name in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.

8. By copying, installing or otherwise using Python, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.

doctest — Test interactive Python examples

Source code: Lib/doctest.py


The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown. There are several common ways to use doctest:

  • To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented.

  • To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.

  • To write tutorial documentation for a package, liberally illustrated with input-output examples. Depending on whether the examples or the expository text are emphasized, this has the flavor of “literate testing” or “executable documentation”.

Here’s a complete but small example module:

"""
This is the "example" module.

The example module supplies one function, factorial().  For example,

>>> factorial(5)
120
"""

def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> factorial(30)
    265252859812191058636308480000000
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: n must be >= 0

    Factorials of floats are OK, but the float must be an exact integer:
    >>> factorial(30.1)
    Traceback (most recent call last):
        ...
    ValueError: n must be exact integer
    >>> factorial(30.0)
    265252859812191058636308480000000

    It must also not be ridiculously large:
    >>> factorial(1e100)
    Traceback (most recent call last):
        ...
    OverflowError: n too large
    """

    import math
    if not n >= 0:
        raise ValueError("n must be >= 0")
    if math.floor(n) != n:
        raise ValueError("n must be exact integer")
    if n+1 == n:  # catch a value like 1e300
        raise OverflowError("n too large")
    result = 1
    factor = 2
    while factor <= n:
        result *= factor
        factor += 1
    return result


if __name__ == "__main__":
    import doctest
    doctest.testmod()

If you run example.py directly from the command line, doctest works its magic:

$ python example.py
$

There’s no output! That’s normal, and it means all the examples worked. Pass -v to the script, and doctest prints a detailed log of what it’s trying, and prints a summary at the end:

$ python example.py -v
Trying:
    factorial(5)
Expecting:
    120
ok
Trying:
    [factorial(n) for n in range(6)]
Expecting:
    [1, 1, 2, 6, 24, 120]
ok

And so on, eventually ending with:

Trying:
    factorial(1e100)
Expecting:
    Traceback (most recent call last):
        ...
    OverflowError: n too large
ok
2 items passed all tests:
   1 test in __main__
   6 tests in __main__.factorial
7 tests in 2 items.
7 passed.
Test passed.
$

That’s all you need to know to start making productive use of doctest! Jump in. The following sections provide full details. Note that there are many examples of doctests in the standard Python test suite and libraries. Especially useful examples can be found in the standard test file Lib/test/test_doctest/test_doctest.py.

Added in version 3.13: Output is colorized by default and can be controlled using environment variables.

Simple Usage: Checking Examples in Docstrings

The simplest way to start using doctest (but not necessarily the way you’ll continue to do it) is to end each module M with:

if __name__ == "__main__":
    import doctest
    doctest.testmod()

doctest then examines docstrings in module M.

Running the module as a script causes the examples in the docstrings to get executed and verified:

python M.py

This won’t display anything unless an example fails, in which case the failing example(s) and the cause(s) of the failure(s) are printed to stdout, and the final line of output is ***Test Failed*** N failures., where N is the number of examples that failed.

Run it with the -v switch instead:

python M.py -v

and a detailed report of all examples tried is printed to standard output, along with assorted summaries at the end.

You can force verbose mode by passing verbose=True to testmod(), or prohibit it by passing verbose=False. In either of those cases, sys.argv is not examined by testmod() (so passing -v or not has no effect).

There is also a command line shortcut for running testmod(), see section Command-line Usage.

For more information on testmod(), see section Basic API.

Simple Usage: Checking Examples in a Text File

Another simple application of doctest is testing interactive examples in a text file. This can be done with the testfile() function:

import doctest
doctest.testfile("example.txt")

That short script executes and verifies any interactive Python examples contained in the file example.txt. The file content is treated as if it were a single giant docstring; the file doesn’t need to contain a Python program! For example, perhaps example.txt contains this:

The ``example`` module
======================

Using ``factorial``
-------------------

This is an example text file in reStructuredText format.  First import
``factorial`` from the ``example`` module:

    >>> from example import factorial

Now use it:

    >>> factorial(6)
    120

Running doctest.testfile("example.txt") then finds the error in this documentation:

File "./example.txt", line 14, in example.txt
Failed example:
    factorial(6)
Expected:
    120
Got:
    720

As with testmod(), testfile() won’t display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to stdout, using the same format as testmod().

By default, testfile() looks for files in the calling module’s directory. See section Basic API for a description of the optional arguments that can be used to tell it to look for files in other locations.

Like testmod(), testfile()’s verbosity can be set with the -v command-line switch or with the optional keyword argument verbose.

There is also a command line shortcut for running testfile(), see section Command-line Usage.

For more information on testfile(), see section Basic API.

Command-line Usage

The doctest module can be invoked as a script from the command line:

python -m doctest [-v] [-o OPTION] [-f] file [file ...]
-v, --verbose

Detailed report of all examples tried is printed to standard output, along with assorted summaries at the end:

python -m doctest -v example.py

This will import example.py as a standalone module and run testmod() on it. Note that this may not work correctly if the file is part of a package and imports other submodules from that package.

If the file name does not end with .py, doctest infers that it must be run with testfile() instead:

python -m doctest -v example.txt
-o, --option <option>

Option flags control various aspects of doctest’s behavior, see section Option Flags.

Added in version 3.4.

-f, --fail-fast

This is shorthand for -o FAIL_FAST.

Added in version 3.4.

How It Works

This section examines in detail how doctest works: which docstrings it looks at, how it finds interactive examples, what execution context it uses, how it handles exceptions, and how option flags can be used to control its behavior. This is the information that you need to know to write doctest examples; for information about actually running doctest on these examples, see the following sections.

Which Docstrings Are Examined?

The module docstring, and all function, class and method docstrings are searched. Objects imported into the module are not searched.

In addition, there are cases when you want tests to be part of a module but not part of the help text, which requires that the tests not be included in the docstring. Doctest looks for a module-level variable called __test__ and uses it to locate other tests. If M.__test__ exists, it must be a dict, and each entry maps a (string) name to a function object, class object, or string. Function and class object docstrings found from M.__test__ are searched, and strings are treated as if they were docstrings. In output, a key K in M.__test__ appears with name M.__test__.K.

For example, place this block of code at the top of example.py:

__test__ = {
    'numbers': """
>>> factorial(6)
720

>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
"""
}

The value of example.__test__["numbers"] will be treated as a docstring and all the tests inside it will be run. It is important to note that the value can be mapped to a function, class object, or module; if so, doctest searches them recursively for docstrings, which are then scanned for tests.

Any classes found are recursively searched similarly, to test docstrings in their contained methods and nested classes.

Note

doctest can only automatically discover classes and functions that are defined at the module level or inside other classes.

Since nested classes and functions only exist when an outer function is called, they cannot be discovered. Define them outside to make them visible.

How are Docstring Examples Recognized?

In most cases a copy-and-paste of an interactive console session works fine, but doctest isn’t trying to do an exact emulation of any specific Python shell.

>>> # comments are ignored
>>> x = 12
>>> x
12
>>> if x == 13:
...     print("yes")
... else:
...     print("no")
...     print("NO")
...     print("NO!!!")
...
no
NO
NO!!!
>>>

Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line.

The fine print:

  • Expected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output. If expected output does contain a blank line, put <BLANKLINE> in your doctest example each place a blank line is expected.

  • All hard tab characters are expanded to spaces, using 8-column tab stops. Tabs in output generated by the tested code are not modified. Because any hard tabs in the sample output are expanded, this means that if the code output includes hard tabs, the only way the doctest can pass is if the NORMALIZE_WHITESPACE option or directive is in effect. Alternatively, the test can be rewritten to capture the output and compare it to an expected value as part of the test. This handling of tabs in the source was arrived at through trial and error, and has proven to be the least error prone way of handling them. It is possible to use a different algorithm for handling tabs by writing a custom DocTestParser class.

  • Output to stdout is captured, but not output to stderr (exception tracebacks are captured via a different means).

  • If you continue a line via backslashing in an interactive session, or for any other reason use a backslash, you should use a raw docstring, which will preserve your backslashes exactly as you type them:

    >>> def f(x):
    ...     r'''Backslashes in a raw docstring: m\n'''
    ...
    >>> print(f.__doc__)
    Backslashes in a raw docstring: m\n
    

    Otherwise, the backslash will be interpreted as part of the string. For example, the \n above would be interpreted as a newline character. Alternatively, you can double each backslash in the doctest version (and not use a raw string):

    >>> def f(x):
    ...     '''Backslashes in a raw docstring: m\\n'''
    ...
    >>> print(f.__doc__)
    Backslashes in a raw docstring: m\n
    
  • The starting column doesn’t matter:

    >>> assert "Easy!"
          >>> import math
              >>> math.floor(1.9)
              1
    

    and as many leading whitespace characters are stripped from the expected output as appeared in the initial '>>> ' line that started the example.

What’s the Execution Context?

By default, each time doctest finds a docstring to test, it uses a shallow copy of M’s globals, so that running tests doesn’t change the module’s real globals, and so that one test in M can’t leave behind crumbs that accidentally allow another test to work. This means examples can freely use any names defined at top-level in M, and names defined earlier in the docstring being run. Examples cannot see names defined in other docstrings.

You can force use of your own dict as the execution context by passing globs=your_dict to testmod() or testfile() instead.

What About Exceptions?

No problem, provided that the traceback is the only output produced by the example: just paste in the traceback. [1] Since tracebacks contain details that are likely to change rapidly (for example, exact file paths and line numbers), this is one case where doctest works hard to be flexible in what it accepts.

Simple example:

>>> [1, 2, 3].remove(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

That doctest succeeds if ValueError is raised, with the list.remove(x): x not in list detail as shown.

The expected output for an exception must start with a traceback header, which may be either of the following two lines, indented the same as the first line of the example:

Traceback (most recent call last):
Traceback (innermost last):

The traceback header is followed by an optional traceback stack, whose contents are ignored by doctest. The traceback stack is typically omitted, or copied verbatim from an interactive session.

The traceback stack is followed by the most interesting part: the line(s) containing the exception type and detail. This is usually the last line of a traceback, but can extend across multiple lines if the exception has a multi-line detail:

>>> raise ValueError('multi\n    line\ndetail')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: multi
    line
detail

The last three lines (starting with ValueError) are compared against the exception’s type and detail, and the rest are ignored.

Best practice is to omit the traceback stack, unless it adds significant documentation value to the example. So the last example is probably better as:

>>> raise ValueError('multi\n    line\ndetail')
Traceback (most recent call last):
    ...
ValueError: multi
    line
detail

Note that tracebacks are treated very specially. In particular, in the rewritten example, the use of ... is independent of doctest’s ELLIPSIS option. The ellipsis in that example could be left out, or could just as well be three (or three hundred) commas or digits, or an indented transcript of a Monty Python skit.

Some details you should read once, but won’t need to remember:

  • Doctest can’t guess whether your expected output came from an exception traceback or from ordinary printing. So, e.g., an example that expects ValueError: 42 is prime will pass whether ValueError is actually raised or if the example merely prints that traceback text. In practice, ordinary output rarely begins with a traceback header line, so this doesn’t create real problems.

  • Each line of the traceback stack (if present) must be indented further than the first line of the example, or start with a non-alphanumeric character. The first line following the traceback header indented the same and starting with an alphanumeric is taken to be the start of the exception detail. Of course this does the right thing for genuine tracebacks.

  • When the IGNORE_EXCEPTION_DETAIL doctest option is specified, everything following the leftmost colon and any module information in the exception name is ignored.

  • The interactive shell omits the traceback header line for some SyntaxErrors. But doctest uses the traceback header line to distinguish exceptions from non-exceptions. So in the rare case where you need to test a SyntaxError that omits the traceback header, you will need to manually add the traceback header line to your test example.

  • For some exceptions, Python displays the position of the error using ^ markers and tildes:

    >>> 1 + None
      File "<stdin>", line 1
        1 + None
        ~~^~~~~~
    TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
    

    Since the lines showing the position of the error come before the exception type and detail, they are not checked by doctest. For example, the following test would pass, even though it puts the ^ marker in the wrong location:

    >>> 1 + None
      File "<stdin>", line 1
        1 + None
        ^~~~~~~~
    TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
    

Option Flags

A number of option flags control various aspects of doctest’s behavior. Symbolic names for the flags are supplied as module constants, which can be bitwise ORed together and passed to various functions. The names can also be used in doctest directives, and may be passed to the doctest command line interface via the -o option.

The first group of options define test semantics, controlling aspects of how doctest decides whether actual output matches an example’s expected output:

doctest.DONT_ACCEPT_TRUE_FOR_1

By default, if an expected output block contains just 1, an actual output block containing just 1 or just True is considered to be a match, and similarly for 0 versus False. When DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution is allowed. The default behavior caters to that Python changed the return type of many functions from integer to boolean; doctests expecting “little integer” output still work in these cases. This option will probably go away, but not for several years.

doctest.DONT_ACCEPT_BLANKLINE

By default, if an expected output block contains a line containing only the string <BLANKLINE>, then that line will match a blank line in the actual output. Because a genuinely blank line delimits the expected output, this is the only way to communicate that a blank line is expected. When DONT_ACCEPT_BLANKLINE is specified, this substitution is not allowed.

doctest.NORMALIZE_WHITESPACE

When specified, all sequences of whitespace (blanks and newlines) are treated as equal. Any sequence of whitespace within the expected output will match any sequence of whitespace within the actual output. By default, whitespace must match exactly. NORMALIZE_WHITESPACE is especially useful when a line of expected output is very long, and you want to wrap it across multiple lines in your source.

doctest.ELLIPSIS

When specified, an ellipsis marker (...) in the expected output can match any substring in the actual output. This includes substrings that span line boundaries, and empty substrings, so it’s best to keep usage of this simple. Complicated uses can lead to the same kinds of “oops, it matched too much!” surprises that .* is prone to in regular expressions.

doctest.IGNORE_EXCEPTION_DETAIL

When specified, doctests expecting exceptions pass so long as an exception of the expected type is raised, even if the details (message and fully qualified exception name) don’t match.

For example, an example expecting ValueError: 42 will pass if the actual exception raised is ValueError: 3*14, but will fail if, say, a TypeError is raised instead. It will also ignore any fully qualified name included before the exception class, which can vary between implementations and versions of Python and the code/libraries in use. Hence, all three of these variations will work with the flag specified:

>>> raise Exception('message')
Traceback (most recent call last):
Exception: message

>>> raise Exception('message')
Traceback (most recent call last):
builtins.Exception: message

>>> raise Exception('message')
Traceback (most recent call last):
__main__.Exception: message

Note that ELLIPSIS can also be used to ignore the details of the exception message, but such a test may still fail based on whether the module name is present or matches exactly.

Changed in version 3.2: IGNORE_EXCEPTION_DETAIL now also ignores any information relating to the module containing the exception under test.

doctest.SKIP

When specified, do not run the example at all. This can be useful in contexts where doctest examples serve as both documentation and test cases, and an example should be included for documentation purposes, but should not be checked. E.g., the example’s output might be random; or the example might depend on resources which would be unavailable to the test driver.

The SKIP flag can also be used for temporarily “commenting out” examples.

doctest.COMPARISON_FLAGS

A bitmask or’ing together all the comparison flags above.

The second group of options controls how test failures are reported:

doctest.REPORT_UDIFF

When specified, failures that involve multi-line expected and actual outputs are displayed using a unified diff.

doctest.REPORT_CDIFF

When specified, failures that involve multi-line expected and actual outputs will be displayed using a context diff.

doctest.REPORT_NDIFF

When specified, differences are computed by difflib.Differ, using the same algorithm as the popular ndiff.py utility. This is the only method that marks differences within lines as well as across lines. For example, if a line of expected output contains digit 1 where actual output contains letter l, a line is inserted with a caret marking the mismatching column positions.

doctest.REPORT_ONLY_FIRST_FAILURE

When specified, display the first failing example in each doctest, but suppress output for all remaining examples. This will prevent doctest from reporting correct examples that break because of earlier failures; but it might also hide incorrect examples that fail independently of the first failure. When REPORT_ONLY_FIRST_FAILURE is specified, the remaining examples are still run, and still count towards the total number of failures reported; only the output is suppressed.

doctest.FAIL_FAST

When specified, exit after the first failing example and don’t attempt to run the remaining examples. Thus, the number of failures reported will be at most 1. This flag may be useful during debugging, since examples after the first failure won’t even produce debugging output.

doctest.REPORTING_FLAGS

A bitmask or’ing together all the reporting flags above.

There is also a way to register new option flag names, though this isn’t useful unless you intend to extend doctest internals via subclassing:

doctest.register_optionflag(name)

Create a new option flag with a given name, and return the new flag’s integer value. register_optionflag() can be used when subclassing OutputChecker or DocTestRunner to create new options that are supported by your subclasses. register_optionflag() should always be called using the following idiom:

MY_FLAG = register_optionflag('MY_FLAG')

Directives

Doctest directives may be used to modify the option flags for an individual example. Doctest directives are special Python comments following an example’s source code:

directive:             "#" "doctest:" directive_options
directive_options:     directive_option ("," directive_option)*
directive_option:      on_or_off directive_option_name
on_or_off:             "+" | "-"
directive_option_name: "DONT_ACCEPT_BLANKLINE" | "NORMALIZE_WHITESPACE" | ...

Whitespace is not allowed between the + or - and the directive option name. The directive option name can be any of the option flag names explained above.

An example’s doctest directives modify doctest’s behavior for that single example. Use + to enable the named behavior, or - to disable it.

For example, this test passes:

>>> print(list(range(20)))  # doctest: +NORMALIZE_WHITESPACE
[0,   1,  2,  3,  4,  5,  6,  7,  8,  9,
10,  11, 12, 13, 14, 15, 16, 17, 18, 19]

Without the directive it would fail, both because the actual output doesn’t have two blanks before the single-digit list elements, and because the actual output is on a single line. This test also passes, and also requires a directive to do so:

>>> print(list(range(20)))  # doctest: +ELLIPSIS
[0, 1, ..., 18, 19]

Multiple directives can be used on a single physical line, separated by commas:

>>> print(list(range(20)))  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
[0,    1, ...,   18,    19]

If multiple directive comments are used for a single example, then they are combined:

>>> print(list(range(20)))  # doctest: +ELLIPSIS
...                         # doctest: +NORMALIZE_WHITESPACE
[0,    1, ...,   18,    19]

As the previous example shows, you can add ... lines to your example containing only directives. This can be useful when an example is too long for a directive to comfortably fit on the same line:

>>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))
... # doctest: +ELLIPSIS
[0, ..., 4, 10, ..., 19, 30, ..., 39]

Note that since all options are disabled by default, and directives apply only to the example they appear in, enabling options (via + in a directive) is usually the only meaningful choice. However, option flags can also be passed to functions that run doctests, establishing different defaults. In such cases, disabling an option via - in a directive can be useful.

Warnings

doctest is serious about requiring exact matches in expected output. If even a single character doesn’t match, the test fails. This will probably surprise you a few times, as you learn exactly what Python does and doesn’t guarantee about output. For example, when printing a set, Python doesn’t guarantee that the element is printed in any particular order, so a test like

>>> foo()
{"spam", "eggs"}

is vulnerable! One workaround is to do

>>> foo() == {"spam", "eggs"}
True

instead. Another is to do

>>> d = sorted(foo())
>>> d
['eggs', 'spam']

There are others, but you get the idea.

Another bad idea is to print things that embed an object address, like

>>> id(1.0)  # certain to fail some of the time
7948648
>>> class C: pass
>>> C()  # the default repr() for instances embeds an address
<C object at 0x00AC18F0>

The ELLIPSIS directive gives a nice approach for the last example:

>>> C()  # doctest: +ELLIPSIS
<C object at 0x...>

Floating-point numbers are also subject to small output variations across platforms, because Python defers to the platform C library for some floating-point calculations, and C libraries vary widely in quality here.

>>> 1000**0.1  # risky
1.9952623149688797
>>> round(1000**0.1, 9) # safer
1.995262315
>>> print(f'{1000**0.1:.4f}') # much safer
1.9953

Numbers of the form I/2.**J are safe across all platforms, and I often contrive doctest examples to produce numbers of that form:

>>> 3./4  # utterly safe
0.75

Simple fractions are also easier for people to understand, and that makes for better documentation.

Basic API

The functions testmod() and testfile() provide a simple interface to doctest that should be sufficient for most basic uses. For a less formal introduction to these two functions, see sections Simple Usage: Checking Examples in Docstrings and Simple Usage: Checking Examples in a Text File.

doctest.testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=DocTestParser(), encoding=None)

All arguments except filename are optional, and should be specified in keyword form.

Test examples in the file named filename. Return (failure_count, test_count).

Optional argument module_relative specifies how the filename should be interpreted:

  • If module_relative is True (the default), then filename specifies an OS-independent module-relative path. By default, this path is relative to the calling module’s directory; but if the package argument is specified, then it is relative to that package. To ensure OS-independence, filename should use / characters to separate path segments, and may not be an absolute path (i.e., it may not begin with /).

  • If module_relative is False, then filename specifies an OS-specific path. The path may be absolute or relative; relative paths are resolved with respect to the current working directory.

Optional argument name gives the name of the test; by default, or if None, os.path.basename(filename) is used.

Optional argument package is a Python package or the name of a Python package whose directory should be used as the base directory for a module-relative filename. If no package is specified, then the calling module’s directory is used as the base directory for module-relative filenames. It is an error to specify package if module_relative is False.

Optional argument globs gives a dict to be used as the globals when executing examples. A new shallow copy of this dict is created for the doctest, so its examples start with a clean slate. By default, or if None, a new empty dict is used.

Optional argument extraglobs gives a dict merged into the globals used to execute examples. This works like dict.update(): if globs and extraglobs have a common key, the associated value in extraglobs appears in the combined dict. By default, or if None, no extra globals are used. This is an advanced feature that allows parameterization of doctests. For example, a doctest can be written for a base class, using a generic name for the class, then reused to test any number of subclasses by passing an extraglobs dict mapping the generic name to the subclass to be tested.

Optional argument verbose prints lots of stuff if true, and prints only failures if false; by default, or if None, it’s true if and only if '-v' is in sys.argv.

Optional argument report prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else the summary is very brief (in fact, empty if all tests passed).

Optional argument optionflags (default value 0) takes the bitwise OR of option flags. See section Option Flags.

Optional argument raise_on_error defaults to false. If true, an exception is raised upon the first failure or unexpected exception in an example. This allows failures to be post-mortem debugged. Default behavior is to continue running examples.

Optional argument parser specifies a DocTestParser (or subclass) that should be used to extract tests from the files. It defaults to a normal parser (i.e., DocTestParser()).

Optional argument encoding specifies an encoding that should be used to convert the file to unicode.

doctest.testmod(m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False)

All arguments are optional, and all except for m should be specified in keyword form.

Test examples in docstrings in functions and classes reachable from module m (or module __main__ if m is not supplied or is None), starting with m.__doc__.

Also test examples reachable from dict m.__test__, if it exists. m.__test__ maps names (strings) to functions, classes and strings; function and class docstrings are searched for examples; strings are searched directly, as if they were docstrings.

Only docstrings attached to objects belonging to module m are searched.

Return (failure_count, test_count).

Optional argument name gives the name of the module; by default, or if None, m.__name__ is used.

Optional argument exclude_empty defaults to false. If true, objects for which no doctests are found are excluded from consideration. The default is a backward compatibility hack, so that code still using doctest.master.summarize in conjunction with testmod() continues to get output for objects with no tests. The exclude_empty argument to the newer DocTestFinder constructor defaults to true.

Optional arguments extraglobs, verbose, report, optionflags, raise_on_error, and globs are the same as for function testfile() above, except that globs defaults to m.__dict__.

doctest.run_docstring_examples(f, globs, verbose=False, name='NoName', compileflags=None, optionflags=0)

Test examples associated with object f; for example, f may be a string, a module, a function, or a class object.

A shallow copy of dictionary argument globs is used for the execution context.

Optional argument name is used in failure messages, and defaults to "NoName".

If optional argument verbose is true, output is generated even if there are no failures. By default, output is generated only in case of an example failure.

Optional argument compileflags gives the set of flags that should be used by the Python compiler when running the examples. By default, or if None, flags are deduced corresponding to the set of future features found in globs.

Optional argument optionflags works as for function testfile() above.

Unittest API

As your collection of doctest’ed modules grows, you’ll want a way to run all their doctests systematically. doctest provides two functions that can be used to create unittest test suites from modules and text files containing doctests. To integrate with unittest test discovery, include a load_tests function in your test module:

import unittest
import doctest
import my_module_with_doctests

def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
    return tests

There are two main functions for creating unittest.TestSuite instances from text files and modules with doctests:

doctest.DocFileSuite(*paths, module_relative=True, package=None, setUp=None, tearDown=None, globs=None, optionflags=0, parser=DocTestParser(), encoding=None)

Convert doctest tests from one or more text files to a unittest.TestSuite.

The returned unittest.TestSuite is to be run by the unittest framework and runs the interactive examples in each file. Each file is run as a separate unit test, and each example in a file is run as a subtest. If any example in a file fails, then the synthesized unit test fails. The traceback for failure or error contains the name of the file containing the test and a (sometimes approximate) line number. If all the examples in a file are skipped, then the synthesized unit test is also marked as skipped.

Pass one or more paths (as strings) to text files to be examined.

Options may be provided as keyword arguments:

Optional argument module_relative specifies how the filenames in paths should be interpreted:

  • If module_relative is True (the default), then each filename in paths specifies an OS-independent module-relative path. By default, this path is relative to the calling module’s directory; but if the package argument is specified, then it is relative to that package. To ensure OS-independence, each filename should use / characters to separate path segments, and may not be an absolute path (i.e., it may not begin with /).

  • If module_relative is False, then each filename in paths specifies an OS-specific path. The path may be absolute or relative; relative paths are resolved with respect to the current working directory.

Optional argument package is a Python package or the name of a Python package whose directory should be used as the base directory for module-relative filenames in paths. If no package is specified, then the calling module’s directory is used as the base directory for module-relative filenames. It is an error to specify package if module_relative is False.

Optional argument setUp specifies a set-up function for the test suite. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed.

Optional argument tearDown specifies a tear-down function for the test suite. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed.

Optional argument globs is a dictionary containing the initial global variables for the tests. A new copy of this dictionary is created for each test. By default, globs is a new empty dictionary.

Optional argument optionflags specifies the default doctest options for the tests, created by or-ing together individual option flags. See section Option Flags. See function set_unittest_reportflags() below for a better way to set reporting options.

Optional argument parser specifies a DocTestParser (or subclass) that should be used to extract tests from the files. It defaults to a normal parser (i.e., DocTestParser()).

Optional argument encoding specifies an encoding that should be used to convert the file to unicode.

The global __file__ is added to the globals provided to doctests loaded from a text file using DocFileSuite().

Changed in version 3.15: Run each example as a subtest.

doctest.DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, setUp=None, tearDown=None, optionflags=0, checker=None)

Convert doctest tests for a module to a unittest.TestSuite.

The returned unittest.TestSuite is to be run by the unittest framework and runs each doctest in the module. Each docstring is run as a separate unit test, and each example in a docstring is run as a subtest. If any of the doctests fail, then the synthesized unit test fails. The traceback for failure or error contains the name of the file containing the test and a (sometimes approximate) line number. If all the examples in a docstring are skipped, then the synthesized unit test is also marked as skipped.

Optional argument module provides the module to be tested. It can be a module object or a (possibly dotted) module name. If not specified, the module calling this function is used.

Optional argument globs is a dictionary containing the initial global variables for the tests. A new copy of this dictionary is created for each test. By default, globs is the module’s __dict__.

Optional argument extraglobs specifies an extra set of global variables, which is merged into globs. By default, no extra globals are used.

Optional argument test_finder is the DocTestFinder object (or a drop-in replacement) that is used to extract doctests from the module.

Optional arguments setUp, tearDown, and optionflags are the same as for function DocFileSuite() above, but they are called for each docstring.

This function uses the same search technique as testmod().

Changed in version 3.5: DocTestSuite() returns an empty unittest.TestSuite if module contains no docstrings instead of raising ValueError.

Changed in version 3.15: Run each example as a subtest.

Under the covers, DocTestSuite() creates a unittest.TestSuite out of doctest.DocTestCase instances, and DocTestCase is a subclass of unittest.TestCase. DocTestCase isn’t documented here (it’s an internal detail), but studying its code can answer questions about the exact details of unittest integration.

Similarly, DocFileSuite() creates a unittest.TestSuite out of doctest.DocFileCase instances, and DocFileCase is a subclass of DocTestCase.

So both ways of creating a unittest.TestSuite run instances of DocTestCase. This is important for a subtle reason: when you run doctest functions yourself, you can control the doctest options in use directly, by passing option flags to doctest functions. However, if you’re writing a unittest framework, unittest ultimately controls when and how tests get run. The framework author typically wants to control doctest reporting options (perhaps, e.g., specified by command line options), but there’s no way to pass options through unittest to doctest test runners.

For this reason, doctest also supports a notion of doctest reporting flags specific to unittest support, via this function:

doctest.set_unittest_reportflags(flags)

Set the doctest reporting flags to use.

Argument flags takes the bitwise OR of option flags. See section Option Flags. Only “reporting flags” can be used.

This is a module-global setting, and affects all future doctests run by module unittest: the runTest() method of DocTestCase looks at the option flags specified for the test case when the DocTestCase instance was constructed. If no reporting flags were specified (which is the typical and expected case), doctest’s unittest reporting flags are bitwise ORed into the option flags, and the option flags so augmented are passed to the DocTestRunner instance created to run the doctest. If any reporting flags were specified when the DocTestCase instance was constructed, doctest’s unittest reporting flags are ignored.

The value of the unittest reporting flags in effect before the function was called is returned by the function.

Advanced API

The basic API is a simple wrapper that’s intended to make doctest easy to use. It is fairly flexible, and should meet most users’ needs; however, if you require more fine-grained control over testing, or wish to extend doctest’s capabilities, then you should use the advanced API.

The advanced API revolves around two container classes, which are used to store the interactive examples extracted from doctest cases:

  • Example: A single Python statement, paired with its expected output.

  • DocTest: A collection of Examples, typically extracted from a single docstring or text file.

Additional processing classes are defined to find, parse, and run, and check doctest examples:

The relationships among these processing classes are summarized in the following diagram:

                            list of:
+------+                   +---------+
|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
+------+    |        ^     +---------+     |       ^    (printed)
            |        |     | Example |     |       |
            v        |     |   ...   |     v       |
           DocTestParser   | Example |   OutputChecker
                           +---------+

DocTest Objects

class doctest.DocTest(examples, globs, name, filename, lineno, docstring)

A collection of doctest examples that should be run in a single namespace. The constructor arguments are used to initialize the attributes of the same names.

DocTest defines the following attributes. They are initialized by the constructor, and should not be modified directly.

examples

A list of Example objects encoding the individual interactive Python examples that should be run by this test.

globs

The namespace (aka globals) that the examples should be run in. This is a dictionary mapping names to values. Any changes to the namespace made by the examples (such as binding new variables) will be reflected in globs after the test is run.

name

A string name identifying the DocTest. Typically, this is the name of the object or file that the test was extracted from.

filename

The name of the file that this DocTest was extracted from; or None if the filename is unknown, or if the DocTest was not extracted from a file.

lineno

The line number within filename where this DocTest begins, or None if the line number is unavailable. This line number is zero-based with respect to the beginning of the file.

docstring

The string that the test was extracted from, or None if the string is unavailable, or if the test was not extracted from a string.

Example Objects

class doctest.Example(source, want, exc_msg=None, lineno=0, indent=0, options=None)

A single interactive example, consisting of a Python statement and its expected output. The constructor arguments are used to initialize the attributes of the same names.

Example defines the following attributes. They are initialized by the constructor, and should not be modified directly.

source

A string containing the example’s source code. This source code consists of a single Python statement, and always ends with a newline; the constructor adds a newline when necessary.

want

The expected output from running the example’s source code (either from stdout, or a traceback in case of exception). want ends with a newline unless no output is expected, in which case it’s an empty string. The constructor adds a newline when necessary.

exc_msg

The exception message generated by the example, if the example is expected to generate an exception; or None if it is not expected to generate an exception. This exception message is compared against the return value of traceback.format_exception_only(). exc_msg ends with a newline unless it’s None. The constructor adds a newline if needed.

lineno

The line number within the string containing this example where the example begins. This line number is zero-based with respect to the beginning of the containing string.

indent

The example’s indentation in the containing string, i.e., the number of space characters that precede the example’s first prompt.

options

A dictionary mapping from option flags to True or False, which is used to override default options for this example. Any option flags not contained in this dictionary are left at their default value (as specified by the DocTestRunner’s optionflags). By default, no options are set.

DocTestFinder objects

class doctest.DocTestFinder(verbose=False, parser=DocTestParser(), recurse=True, exclude_empty=True)

A processing class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. DocTests can be extracted from modules, classes, functions, methods, staticmethods, classmethods, and properties.

The optional argument verbose can be used to display the objects searched by the finder. It defaults to False (no output).

The optional argument parser specifies the DocTestParser object (or a drop-in replacement) that is used to extract doctests from docstrings.

If the optional argument recurse is false, then DocTestFinder.find() will only examine the given object, and not any contained objects.

If the optional argument exclude_empty is false, then DocTestFinder.find() will include tests for objects with empty docstrings.

DocTestFinder defines the following method:

find(obj[, name][, module][, globs][, extraglobs])

Return a list of the DocTests that are defined by obj’s docstring, or by any of its contained objects’ docstrings.

The optional argument name specifies the object’s name; this name will be used to construct names for the returned DocTests. If name is not specified, then obj.__name__ is used.

The optional parameter module is the module that contains the given object. If the module is not specified or is None, then the test finder will attempt to automatically determine the correct module. The object’s module is used:

  • As a default namespace, if globs is not specified.

  • To prevent the DocTestFinder from extracting DocTests from objects that are imported from other modules. (Contained objects with modules other than module are ignored.)

  • To find the name of the file containing the object.

  • To help find the line number of the object within its file.

If module is False, no attempt to find the module will be made. This is obscure, of use mostly in testing doctest itself: if module is False, or is None but cannot be found automatically, then all objects are considered to belong to the (non-existent) module, so all contained objects will (recursively) be searched for doctests.

The globals for each DocTest is formed by combining globs and extraglobs (bindings in extraglobs override bindings in globs). A new shallow copy of the globals dictionary is created for each DocTest. If globs is not specified, then it defaults to the module’s __dict__, if specified, or {} otherwise. If extraglobs is not specified, then it defaults to {}.

DocTestParser objects

class doctest.DocTestParser

A processing class used to extract interactive examples from a string, and use them to create a DocTest object.

DocTestParser defines the following methods:

get_doctest(string, globs, name, filename, lineno)

Extract all doctest examples from the given string, and collect them into a DocTest object.

globs, name, filename, and lineno are attributes for the new DocTest object. See the documentation for DocTest for more information.

get_examples(string, name='<string>')

Extract all doctest examples from the given string, and return them as a list of Example objects. Line numbers are 0-based. The optional argument name is a name identifying this string, and is only used for error messages.

parse(string, name='<string>')

Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument name is a name identifying this string, and is only used for error messages.

TestResults objects

class doctest.TestResults(failed, attempted)
failed

Number of failed tests.

attempted

Number of attempted tests.

skipped

Number of skipped tests.

Added in version 3.13.

DocTestRunner objects

class doctest.DocTestRunner(checker=None, verbose=None, optionflags=0)

A processing class used to execute and verify the interactive examples in a DocTest.

The comparison between expected outputs and actual outputs is done by an OutputChecker. This comparison may be customized with a number of option flags; see section Option Flags for more information. If the option flags are insufficient, then the comparison may also be customized by passing a subclass of OutputChecker to the constructor.

The test runner’s display output can be controlled in two ways. First, an output function can be passed to run(); this function will be called with strings that should be displayed. It defaults to sys.stdout.write. If capturing the output is not sufficient, then the display output can be also customized by subclassing DocTestRunner, and overriding the methods report_skip(), report_start(), report_success(), report_unexpected_exception(), and report_failure().

The optional keyword argument checker specifies the OutputChecker object (or drop-in replacement) that should be used to compare the expected outputs to the actual outputs of doctest examples.

The optional keyword argument verbose controls the DocTestRunner’s verbosity. If verbose is True, then information is printed about each example, as it is run. If verbose is False, then only failures are printed. If verbose is unspecified, or None, then verbose output is used iff the command-line switch -v is used.

The optional keyword argument optionflags can be used to control how the test runner compares expected output to actual output, and how it displays failures. For more information, see section Option Flags.

The test runner accumulates statistics. The aggregated number of attempted, failed and skipped examples is also available via the tries, failures and skips attributes. The run() and summarize() methods return a TestResults instance.

DocTestRunner defines the following methods:

report_skip(out, test, example)

Report that the given example was skipped. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.

example is the example about to be processed. test is the test containing example. out is the output function that was passed to DocTestRunner.run().

Added in version 3.15.

report_start(out, test, example)

Report that the test runner is about to process the given example. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.

example is the example about to be processed. test is the test containing example. out is the output function that was passed to DocTestRunner.run().

report_success(out, test, example, got)

Report that the given example ran successfully. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.

example is the example about to be processed. got is the actual output from the example. test is the test containing example. out is the output function that was passed to DocTestRunner.run().

report_failure(out, test, example, got)

Report that the given example failed. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.

example is the example about to be processed. got is the actual output from the example. test is the test containing example. out is the output function that was passed to DocTestRunner.run().

report_unexpected_exception(out, test, example, exc_info)

Report that the given example raised an unexpected exception. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.

example is the example about to be processed. exc_info is a tuple containing information about the unexpected exception (as returned by sys.exc_info()). test is the test containing example. out is the output function that was passed to DocTestRunner.run().

run(test, compileflags=None, out=None, clear_globs=True)

Run the examples in test (a DocTest object), and display the results using the writer function out. Return a TestResults instance.

The examples are run in the namespace test.globs. If clear_globs is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after the test completes, then use clear_globs=False.

compileflags gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to globs.

The output of each example is checked using the DocTestRunner’s output checker, and the results are formatted by the DocTestRunner.report_*() methods.

summarize(verbose=None)

Print a summary of all the test cases that have been run by this DocTestRunner, and return a TestResults instance.

The optional verbose argument controls how detailed the summary is. If the verbosity is not specified, then the DocTestRunner’s verbosity is used.

DocTestParser has the following attributes:

tries

Number of attempted examples.

failures

Number of failed examples.

skips

Number of skipped examples.

Added in version 3.13.

OutputChecker objects

class doctest.OutputChecker

A class used to check the whether the actual output from a doctest example matches the expected output. OutputChecker defines two methods: check_output(), which compares a given pair of outputs, and returns True if they match; and output_difference(), which returns a string describing the differences between two outputs.

OutputChecker defines the following methods:

check_output(want, got, optionflags)

Return True iff the actual output from an example (got) matches the expected output (want). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See section Option Flags for more information about option flags.

output_difference(example, got, optionflags)

Return a string describing the differences between the expected output for a given example (example) and the actual output (got). optionflags is the set of option flags used to compare want and got.

Debugging

Doctest provides several mechanisms for debugging doctest examples:

  • Several functions convert doctests to executable Python programs, which can be run under the Python debugger, pdb.

  • The DebugRunner class is a subclass of DocTestRunner that raises an exception for the first failing example, containing information about that example. This information can be used to perform post-mortem debugging on the example.

  • The unittest cases generated by DocTestSuite() support the debug() method defined by unittest.TestCase.

  • You can add a call to pdb.set_trace() in a doctest example, and you’ll drop into the Python debugger when that line is executed. Then you can inspect current values of variables, and so on. For example, suppose a.py contains just this module docstring:

    """
    >>> def f(x):
    ...     g(x*2)
    >>> def g(x):
    ...     print(x+3)
    ...     import pdb; pdb.set_trace()
    >>> f(3)
    9
    """
    

    Then an interactive Python session may look like this:

    >>> import a, doctest
    >>> doctest.testmod(a)
    --Return--
    > <doctest a[1]>(3)g()->None
    -> import pdb; pdb.set_trace()
    (Pdb) list
      1     def g(x):
      2         print(x+3)
      3  ->     import pdb; pdb.set_trace()
    [EOF]
    (Pdb) p x
    6
    (Pdb) step
    --Return--
    > <doctest a[0]>(2)f()->None
    -> g(x*2)
    (Pdb) list
      1     def f(x):
      2  ->     g(x*2)
    [EOF]
    (Pdb) p x
    3
    (Pdb) step
    --Return--
    > <doctest a[2]>(1)?()->None
    -> f(3)
    (Pdb) cont
    (0, 3)
    >>>
    

Functions that convert doctests to Python code, and possibly run the synthesized code under the debugger:

doctest.script_from_examples(s)

Convert text with examples to a script.

Argument s is a string containing doctest examples. The string is converted to a Python script, where doctest examples in s are converted to regular code, and everything else is converted to Python comments. The generated script is returned as a string. For example,

import doctest
print(doctest.script_from_examples(r"""
    Set x and y to 1 and 2.
    >>> x, y = 1, 2

    Print their sum:
    >>> print(x+y)
    3
"""))

displays:

# Set x and y to 1 and 2.
x, y = 1, 2
#
# Print their sum:
print(x+y)
# Expected:
## 3

This function is used internally by other functions (see below), but can also be useful when you want to transform an interactive Python session into a Python script.

doctest.testsource(module, name)

Convert the doctest for an object to a script.

Argument module is a module object, or dotted name of a module, containing the object whose doctests are of interest. Argument name is the name (within the module) of the object with the doctests of interest. The result is a string, containing the object’s docstring converted to a Python script, as described for script_from_examples() above. For example, if module a.py contains a top-level function f(), then

import a, doctest
print(doctest.testsource(a, "a.f"))

prints a script version of function f()’s docstring, with doctests converted to code, and the rest placed in comments.

doctest.debug(module, name, pm=False)

Debug the doctests for an object.

The module and name arguments are the same as for function testsource() above. The synthesized Python script for the named object’s docstring is written to a temporary file, and then that file is run under the control of the Python debugger, pdb.

A shallow copy of module.__dict__ is used for both local and global execution context.

Optional argument pm controls whether post-mortem debugging is used. If pm has a true value, the script file is run directly, and the debugger gets involved only if the script terminates via raising an unhandled exception. If it does, then post-mortem debugging is invoked, via pdb.post_mortem(), passing the traceback object from the unhandled exception. If pm is not specified, or is false, the script is run under the debugger from the start, via passing an appropriate exec() call to pdb.run().

doctest.debug_src(src, pm=False, globs=None)

Debug the doctests in a string.

This is like function debug() above, except that a string containing doctest examples is specified directly, via the src argument.

Optional argument pm has the same meaning as in function debug() above.

Optional argument globs gives a dictionary to use as both local and global execution context. If not specified, or None, an empty dictionary is used. If specified, a shallow copy of the dictionary is used.

The DebugRunner class, and the special exceptions it may raise, are of most interest to testing framework authors, and will only be sketched here. See the source code, and especially DebugRunner’s docstring (which is a doctest!) for more details:

class doctest.DebugRunner(checker=None, verbose=None, optionflags=0)

A subclass of DocTestRunner that raises an exception as soon as a failure is encountered. If an unexpected exception occurs, an UnexpectedException exception is raised, containing the test, the example, and the original exception. If the output doesn’t match, then a DocTestFailure exception is raised, containing the test, the example, and the actual output.

For information about the constructor parameters and methods, see the documentation for DocTestRunner in section Advanced API.

There are two exceptions that may be raised by DebugRunner instances:

exception doctest.DocTestFailure(test, example, got)

An exception raised by DocTestRunner to signal that a doctest example’s actual output did not match its expected output. The constructor arguments are used to initialize the attributes of the same names.

DocTestFailure defines the following attributes:

DocTestFailure.test

The DocTest object that was being run when the example failed.

DocTestFailure.example

The Example that failed.

DocTestFailure.got

The example’s actual output.

exception doctest.UnexpectedException(test, example, exc_info)

An exception raised by DocTestRunner to signal that a doctest example raised an unexpected exception. The constructor arguments are used to initialize the attributes of the same names.

UnexpectedException defines the following attributes:

UnexpectedException.test

The DocTest object that was being run when the example failed.

UnexpectedException.example

The Example that failed.

UnexpectedException.exc_info

A tuple containing information about the unexpected exception, as returned by sys.exc_info().

Soapbox

As mentioned in the introduction, doctest has grown to have three primary uses:

  1. Checking examples in docstrings.

  2. Regression testing.

  3. Executable documentation / literate testing.

These uses have different requirements, and it is important to distinguish them. In particular, filling your docstrings with obscure test cases makes for bad documentation.

When writing a docstring, choose docstring examples with care. There’s an art to this that needs to be learned—it may not be natural at first. Examples should add genuine value to the documentation. A good example can often be worth many words. If done with care, the examples will be invaluable for your users, and will pay back the time it takes to collect them many times over as the years go by and things change. I’m still amazed at how often one of my doctest examples stops working after a “harmless” change.

Doctest also makes an excellent tool for regression testing, especially if you don’t skimp on explanatory text. By interleaving prose and examples, it becomes much easier to keep track of what’s actually being tested, and why. When a test fails, good prose can make it much easier to figure out what the problem is, and how it should be fixed. It’s true that you could write extensive comments in code-based testing, but few programmers do. Many have found that using doctest approaches instead leads to much clearer tests. Perhaps this is simply because doctest makes writing prose a little easier than writing code, while writing comments in code is a little harder. I think it goes deeper than just that: the natural attitude when writing a doctest-based test is that you want to explain the fine points of your software, and illustrate them with examples. This in turn naturally leads to test files that start with the simplest features, and logically progress to complications and edge cases. A coherent narrative is the result, instead of a collection of isolated functions that test isolated bits of functionality seemingly at random. It’s a different attitude, and produces different results, blurring the distinction between testing and explaining.

Regression testing is best confined to dedicated objects or files. There are several options for organizing tests:

  • Write text files containing test cases as interactive examples, and test the files using testfile() or DocFileSuite(). This is recommended, although is easiest to do for new projects, designed from the start to use doctest.

  • Define functions named _regrtest_topic that consist of single docstrings, containing test cases for the named topics. These functions can be included in the same file as the module, or separated out into a separate test file.

  • Define a __test__ dictionary mapping from regression test topics to docstrings containing test cases.

When you have placed your tests in a module, the module can itself be the test runner. When a test fails, you can arrange for your test runner to re-run only the failing doctest while you debug the problem. Here is a minimal example of such a test runner:

if __name__ == '__main__':
    import doctest
    flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST
    if len(sys.argv) > 1:
        name = sys.argv[1]
        if name in globals():
            obj = globals()[name]
        else:
            obj = __test__[name]
        doctest.run_docstring_examples(obj, globals(), name=name,
                                       optionflags=flags)
    else:
        fail, total = doctest.testmod(optionflags=flags)
        print(f"{fail} failures out of {total} tests")

Footnotes

3 . 4 Discussion and Exercises

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

3.4 Discussion and Exercises

Both singly-linked and doubly-linked lists are established techniques, having been used in programs for over 40 years. They are discussed, for example, by Knuth [46, Sections 2.2.3-2.2.5]. Even the SEList data structure seems to be a well-known data structures exercise. The SEList is sometimes referred to as an unrolled linked list [67].

Another way to save space in a doubly-linked list is to use so-called XOR-lists. In an XOR-list, each node, $ \ensuremath{\ensuremath{\mathit{u}}}$, contains only one pointer, called $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{nextprev}}}$, that holds the bitwise exclusive-or of $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{prev}}}$ and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{next}}}$. The list itself needs to store two pointers, one to the $ \ensuremath{\ensuremath{\mathit{dummy}}}$ node and one to $ \ensuremath{\ensuremath{\mathit{dummy}}.\ensuremath{\mathit{next}}}$ (the first node, or $ \ensuremath{\ensuremath{\mathit{dummy}}}$ if the list is empty). This technique uses the fact that, if we have pointers to $ \ensuremath{\ensuremath{\mathit{u}}}$ and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{prev}}}$, then we can extract $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{next}}}$ using the formula

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\math...
...ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{nextprev}}}} \enspace .
$

(Here ^ computes the bitwise exclusive-or of its two arguments.) This technique complicates the code a little and is not possible in some languages, like Java and Python, that have garbage collection but gives a doubly-linked list implementation that requires only one pointer per node. See Sinha's magazine article [68] for a detailed discussion of XOR-lists.

Exercise 3..1   Why is it not possible to use a dummy node in an SLList to avoid all the special cases that occur in the operations $ \ensuremath{\mathrm{push}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{pop}()}$, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{remove}()}$?

Exercise 3..2   Design and implement an SLList method, $ \ensuremath{\mathrm{second\_last}()}$, that returns the second-last element of an SLList. Do this without using the member variable, $ \ensuremath{\ensuremath{\mathit{n}}}$, that keeps track of the size of the list.

Exercise 3..3   Implement the List operations $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$, $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ on an SLList. Each of these operations should run in $ O(1+\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}})$ time.

Exercise 3..4   Design and implement an SLList method, $ \ensuremath{\mathrm{reverse}()}$ that reverses the order of elements in an SLList. This method should run in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time, should not use recursion, should not use any secondary data structures, and should not create any new nodes.

Exercise 3..5   Design and implement SLList and DLList methods called $ \ensuremath{\mathrm{check\_size}()}$. These methods walk through the list and count the number of nodes to see if this matches the value, $ \ensuremath{\ensuremath{\mathit{n}}}$, stored in the list. These methods return nothing, but throw an exception if the size they compute does not match the value of $ \ensuremath{\ensuremath{\mathit{n}}}$.

Exercise 3..6   Try to recreate the code for the $ \ensuremath{\mathrm{add\_before}(\ensuremath{\mathit{w}})}$ operation that creates a node, $ \ensuremath{\ensuremath{\mathit{u}}}$, and adds it in a DLList just before the node $ \ensuremath{\ensuremath{\mathit{w}}}$. Do not refer to this chapter. Even if your code does not exactly match the code given in this book it may still be correct. Test it and see if it works.

The next few exercises involve performing manipulations on DLLists. You should complete them without allocating any new nodes or temporary arrays. They can all be done only by changing the $ \ensuremath{\ensuremath{\mathit{prev}}}$ and $ \ensuremath{\ensuremath{\mathit{next}}}$ values of existing nodes.

Exercise 3..7   Write a DLList method $ \ensuremath{\mathrm{is\_palindrome}()}$ that returns $ \ensuremath{\ensuremath{\mathit{true}}}$ if the list is a palindrome, i.e., the element at position $ \ensuremath{\ensuremath{\mathit{i}}}$ is equal to the element at position $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-i-1$ for all $ i\in\{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1\}$. Your code should run in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time.

Exercise 3..8   Implement a method $ \ensuremath{\mathrm{rotate}(\ensuremath{\mathit{r}})}$ that ``rotates'' a DLList so that list item $ \ensuremath{\ensuremath{\mathit{i}}}$ becomes list item $ (\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}})\bmod \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$. This method should run in $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}},\ensuremath{\ensur...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}\})$ time and should not modify any nodes in the list.

Exercise 3..9   Write a method, $ \ensuremath{\mathrm{truncate}(\ensuremath{\mathit{i}})}$, that truncates a DLList at position $ \ensuremath{\ensuremath{\mathit{i}}}$. After executing this method, the size of the list will be $ \ensuremath{\ensuremath{\mathit{i}}}$ and it should contain only the elements at indices $ 0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}-1$. The return value is another DLList that contains the elements at indices $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1$. This method should run in $ O(\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$ time.

Exercise 3..10   Write a DLList method, $ \ensuremath{\mathrm{absorb}(\ensuremath{\mathit{l_2}})}$, that takes as an argument a DLList, $ \ensuremath{\ensuremath{\mathit{l_2}}}$, empties it and appends its contents, in order, to the receiver. For example, if $ \ensuremath{\ensuremath{\mathit{l_1}}}$ contains $ a,b,c$ and $ \ensuremath{\ensuremath{\mathit{l_2}}}$ contains $ d,e,f$, then after calling $ \ensuremath{\ensuremath{\mathit{l_1}}.\mathrm{absorb}(\ensuremath{\mathit{l_2}})}$, $ \ensuremath{\ensuremath{\mathit{l_1}}}$ will contain $ a,b,c,d,e,f$ and $ \ensuremath{\ensuremath{\mathit{l_2}}}$ will be empty.

Exercise 3..11   Write a method $ \ensuremath{\mathrm{deal}()}$ that removes all the elements with odd-numbered indices from a DLList and return a DLList containing these elements. For example, if $ \ensuremath{\ensuremath{\mathit{l_1}}}$, contains the elements $ a,b,c,d,e,f$, then after calling $ \ensuremath{\ensuremath{\mathit{l_1}}.\mathrm{deal}()}$, $ \ensuremath{\ensuremath{\mathit{l_1}}}$ should contain $ a,c,e$ and a list containing $ b,d,f$ should be returned.

Exercise 3..12   Write a method, $ \ensuremath{\mathrm{reverse}()}$, that reverses the order of elements in a DLList.

Exercise 3..13   This exercise walks you through an implementation of the merge-sort algorithm for sorting a DLList, as discussed in Section 11.1.1.
  1. Write a DLList method called $ \ensuremath{\mathrm{take\_first}(\ensuremath{\mathit{l_2}})}$. This method takes the first node from $ \ensuremath{\ensuremath{\mathit{l_2}}}$ and appends it to the the receiving list. This is equivalent to $ \ensuremath{\mathrm{add}(\mathrm{size}(),\ensuremath{\mathit{l_2}}.\mathrm{remove}(0)})$, except that it should not create a new node.
  2. Write a DLList static method, $ \ensuremath{\mathrm{merge}(\ensuremath{\mathit{l_1}},\ensuremath{\mathit{l_2}})}$, that takes two sorted lists $ \ensuremath{\ensuremath{\mathit{l_1}}}$ and $ \ensuremath{\ensuremath{\mathit{l_2}}}$, merges them, and returns a new sorted list containing the result. This causes $ \ensuremath{\ensuremath{\mathit{l_1}}}$ and $ \ensuremath{\ensuremath{\mathit{l_2}}}$ to be emptied in the proces. For example, if $ \ensuremath{\ensuremath{\mathit{l_1}}}$ contains $ a,c,d$ and $ \ensuremath{\ensuremath{\mathit{l_2}}}$ contains $ b,e,f$, then this method returns a new list containing $ a,b,c,d,e,f$.
  3. Write a DLList method $ \ensuremath{\mathrm{sort}()}$ that sorts the elements contained in the list using the merge sort algorithm. This recursive algorithm works in the following way:
    1. If the list contains 0 or 1 elements then there is nothing to do. Otherwise,
    2. Using the $ \ensuremath{\mathrm{truncate}(\mathrm{size}()/2})$ method, split the list into two lists of approximately equal length, $ \ensuremath{\ensuremath{\mathit{l_1}}}$ and $ \ensuremath{\ensuremath{\mathit{l_2}}}$;
    3. Recursively sort $ \ensuremath{\ensuremath{\mathit{l_1}}}$;
    4. Recursively sort $ \ensuremath{\ensuremath{\mathit{l_2}}}$; and, finally,
    5. Merge $ \ensuremath{\ensuremath{\mathit{l_1}}}$ and $ \ensuremath{\ensuremath{\mathit{l_2}}}$ into a single sorted list.

The next few exercises are more advanced and require a clear understanding of what happens to the minimum value stored in a Stack or Queue as items are added and removed.

Exercise 3..14   Design and implement a MinStack data structure that can store comparable elements and supports the stack operations $ \ensuremath{\mathrm{push}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{pop}()}$, and $ \ensuremath{\mathrm{size}()}$, as well as the $ \ensuremath{\mathrm{min}()}$ operation, which returns the minimum value currently stored in the data structure. All operations should run in constant time.

Exercise 3..15   Design and implement a MinQueue data structure that can store comparable elements and supports the queue operations $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}()}$, and $ \ensuremath{\mathrm{size}()}$, as well as the $ \ensuremath{\mathrm{min}()}$ operation, which returns the minimum value currently stored in the data structure. All operations should run in constant amortized time.

Exercise 3..16   Design and implement a MinDeque data structure that can store comparable elements and supports all the deque operations $ \ensuremath{\mathrm{add\_first}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{add\_last}(\ensuremath{\mathit{x}})}$ $ \ensuremath{\mathrm{remove\_first}()}$, $ \ensuremath{\mathrm{remove\_last}()}$ and $ \ensuremath{\mathrm{size}()}$, and the $ \ensuremath{\mathrm{min}()}$ operation, which returns the minimum value currently stored in the data structure. All operations should run in constant amortized time.

The next exercises are designed to test the reader's understanding of the implementation and analysis of the space-efficient SEList:

Exercise 3..17   Prove that, if an SEList is used like a Stack (so that the only modifications to the SEList are done using $ \ensuremath{\ensuremath{\mathrm{push}(\ensuremath{\mathit{x}})}}\equiv
\ensuremath{\ensuremath{\mathrm{add}(\mathrm{size}(),x})}$ and $ \ensuremath{\ensuremath{\mathrm{pop}()}}\equiv \ensuremath{\ensuremath{\mathrm{remove}(\mathrm{size}()-1})}$), then these operations run in constant amortized time, independent of the value of $ \ensuremath{\ensuremath{\mathit{b}}}$.

Exercise 3..18   Design and implement of a version of an SEList that supports all the Deque operations in constant amortized time per operation, independent of the value of $ \ensuremath{\ensuremath{\mathit{b}}}$.

Exercise 3..19   Explain how to use the bitwise exclusive-or operator, ^, to swap the values of two $ \ensuremath{\ensuremath{\mathit{int}}}$ variables without using a third variable.

opendatastructures.org

11 . 1 Comparison-Based Sorting

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Subsections

11.1 Comparison-Based Sorting

In this section, we present three sorting algorithms: merge-sort, quicksort, and heap-sort. Each of these algorithms takes an input array $ \ensuremath{\ensuremath{\mathit{a}}}$ and sorts the elements of $ \ensuremath{\ensuremath{\mathit{a}}}$ into non-decreasing order in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ (expected) time. These algorithms are all comparison-based. These algorithms don't care what type of data is being sorted; the only operation they do on the data is comparisons using the $ \ensuremath{\mathrm{compare}(\ensuremath{\mathit{a}},\ensuremath{\mathit{b}})}$ method. Recall, from Section 1.2.4, that $ \ensuremath{\mathrm{compare}(\ensuremath{\mathit{a}},\ensuremath{\mathit{b}})}$ returns a negative value if $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}}}<\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}$, a positive value if $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}}}>\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}$, and zero if $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}$.


11.1.1 Merge-Sort

The merge-sort algorithm is a classic example of recursive divide and conquer: If the length of $ \ensuremath{\ensuremath{\mathit{a}}}$ is at most 1, then $ \ensuremath{\ensuremath{\mathit{a}}}$ is already sorted, so we do nothing. Otherwise, we split $ \ensuremath{\ensuremath{\mathit{a}}}$ into two halves, $ \ensuremath{\ensuremath{\ensuremath{\mathit{a_0}}}}=\ensuremath{\ensuremath{\e...
...,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}/2-1]}}$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{a_1}}}}=\ensuremath{\ensuremath{\e...
...ts,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-1]}}$. We recursively sort $ \ensuremath{\ensuremath{\mathit{a_0}}}$ and $ \ensuremath{\ensuremath{\mathit{a_1}}}$, and then we merge (the now sorted) $ \ensuremath{\ensuremath{\mathit{a_0}}}$ and $ \ensuremath{\ensuremath{\mathit{a_1}}}$ to get our fully sorted array $ \ensuremath{\ensuremath{\mathit{a}}}$:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{merge\_sort}...
...bf{return}} \ensuremath{\ensuremath{\mathit{a}}}\\
\end{flushleft}\end{leftbar}
An example is shown in Figure 11.1.

Figure 11.1: The execution of $ \ensuremath{\mathrm{merge\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{c}})}$
\includegraphics[width=\textwidth ]{figs-python/mergesort}

Compared to sorting, merging the two sorted arrays $ \ensuremath{\ensuremath{\mathit{a_0}}}$ and $ \ensuremath{\ensuremath{\mathit{a_1}}}$ is fairly easy. We add elements to $ \ensuremath{\ensuremath{\mathit{a}}}$ one at a time. If $ \ensuremath{\ensuremath{\mathit{a_0}}}$ or $ \ensuremath{\ensuremath{\mathit{a_1}}}$ is empty, then we add the next elements from the other (non-empty) array. Otherwise, we take the minimum of the next element in $ \ensuremath{\ensuremath{\mathit{a_0}}}$ and the next element in $ \ensuremath{\ensuremath{\mathit{a_1}}}$ and add it to $ \ensuremath{\ensuremath{\mathit{a}}}$:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{merge}(\ensu...
...\ensuremath{\mathit{i_1}} \gets \ensuremath{i2}}\\
\end{flushleft}\end{leftbar}
Notice that the $ \ensuremath{\mathrm{merge}(\ensuremath{\mathit{a_0}},\ensuremath{\mathit{a_1}},\ensuremath{\mathit{a}},\ensuremath{\mathit{c}})}$ algorithm performs at most $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1$ comparisons before running out of elements in one of $ \ensuremath{\ensuremath{\mathit{a_0}}}$ or $ \ensuremath{\ensuremath{\mathit{a_1}}}$.

To understand the running-time of merge-sort, it is easiest to think of it in terms of its recursion tree. Suppose for now that $ \ensuremath{\ensuremath{\mathit{n}}}$ is a power of two, so that $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}=2^{\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}$, and $ \log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ is an integer. Refer to Figure 11.2. Merge-sort turns the problem of sorting $ \ensuremath{\ensuremath{\mathit{n}}}$ elements into two problems, each of sorting $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2$ elements. These two subproblem are then turned into two problems each, for a total of four subproblems, each of size $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/4$. These four subproblems become eight subproblems, each of size $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/8$, and so on. At the bottom of this process, $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2$ subproblems, each of size two, are converted into $ \ensuremath{\ensuremath{\mathit{n}}}$ problems, each of size one. For each subproblem of size $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2^{i}$, the time spent merging and copying data is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2^i)$. Since there are $ 2^i$ subproblems of size $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2^i$, the total time spent working on problems of size $ 2^i$, not counting recursive calls, is

$\displaystyle 2^i\times O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2^i) = O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}) \enspace .
$

Therefore, the total amount of time taken by merge-sort is

$\displaystyle \sum_{i=0}^{\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}...
...mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}) \enspace .
$

Figure 11.2: The merge-sort recursion tree.
\includegraphics[width=\textwidth ]{figs-python/mergesort-recursion}

The proof of the following theorem is based on preceding analysis, but has to be a little more careful to deal with the cases where $ \ensuremath{\ensuremath{\mathit{n}}}$ is not a power of 2.

Theorem 11..1   The merge_sort(a) algorithm runs in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time and performs at most $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ comparisons.

Proof. The proof is by induction on $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$. The base case, in which $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}=1$, is trivial; when presented with an array of length 0 or 1 the algorithm simply returns without performing any comparisons.

Merging two sorted lists of total length $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ requires at most $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1$ comparisons. Let $ C(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ denote the maximum number of comparisons performed by $ \ensuremath{\mathrm{merge\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{c}})}$ on an array $ \ensuremath{\ensuremath{\mathit{a}}}$ of length $ \ensuremath{\ensuremath{\mathit{n}}}$. If $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ is even, then we apply the inductive hypothesis to the two subproblems and obtain

$\displaystyle C(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ $\displaystyle \le \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1 + 2C(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2)$    
  $\displaystyle \le \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1 + 2((\ens...
...math{\mathit{n}}}}/2)\log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2))$    
  $\displaystyle = \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1 + \ensurema...
...suremath{\mathit{n}}}}\log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2)$    
  $\displaystyle = \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1 + \ensurema...
...ath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$    
  $\displaystyle < \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} \enspace .$    

The case where $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ is odd is slightly more complicated. For this case, we use two inequalities that are easy to verify:

$\displaystyle \log(x+1) \le \log(x) + 1 \enspace ,$ (11.1)

for all $ x\ge 1$ and

$\displaystyle \log(x+1/2) + \log(x-1/2) \le 2\log(x) \enspace ,$ (11.2)

for all $ x\ge 1/2$. Inequality (11.1) comes from the fact that $ \log(x)+1 = \log(2x)$ while (11.2) follows from the fact that $ \log$ is a concave function. With these tools in hand we have, for odd $ \ensuremath{\ensuremath{\mathit{n}}}$,

$\displaystyle C(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ $\displaystyle \le \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1 + C(\lcei...
...rceil) + C(\lfloor \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2 \rfloor)$    
  $\displaystyle \le \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1 + \lceil ...
...\rfloor\log \lfloor \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2 \rfloor$    
  $\displaystyle = \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1 + (\ensurem...
...t{n}}}}/2 - 1/2) \log (\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2-1/2)$    
  $\displaystyle \le \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1 + \ensure...
...{n}}}}/2+1/2) - \log (\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2-1/2))$    
  $\displaystyle \le \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1 + \ensure...
...th{\mathit{n}}}}\log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2) + 1/2$    
  $\displaystyle < \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} + \ensuremath...
...suremath{\mathit{n}}}}\log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2)$    
  $\displaystyle = \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} + \ensuremath...
...suremath{\mathit{n}}}}(\log\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1)$    
  $\displaystyle = \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} \enspace . \qedhere$    

$ \qedsymbol$

11.1.2 Quicksort

The quicksort algorithm is another classic divide and conquer algorithm. Unlike merge-sort, which does merging after solving the two subproblems, quicksort does all of its work upfront.

Quicksort is simple to describe: Pick a random pivot element, $ \ensuremath{\ensuremath{\mathit{x}}}$, from $ \ensuremath{\ensuremath{\mathit{a}}}$; partition $ \ensuremath{\ensuremath{\mathit{a}}}$ into the set of elements less than $ \ensuremath{\ensuremath{\mathit{x}}}$, the set of elements equal to $ \ensuremath{\ensuremath{\mathit{x}}}$, and the set of elements greater than $ \ensuremath{\ensuremath{\mathit{x}}}$; and, finally, recursively sort the first and third sets in this partition. An example is shown in Figure 11.3.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{quick\_sort}...
...nsuremath{\mathit{q}}-\ensuremath{\mathit{i}})})\\
\end{flushleft}\end{leftbar}

Figure 11.3: An example execution of $ \ensuremath{\mathrm{quick\_sort}(\ensuremath{\mathit{a}},0,14)}$
\includegraphics[scale=0.90909]{figs-python/quicksort}
All of this is done in place, so that instead of making copies of subarrays being sorted, the $ \ensuremath{\mathrm{quick\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{i}},\ensuremath{\mathit{n}},\ensuremath{\mathit{c}})}$ method only sorts the subarray $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}},\ld...
...th{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}+\ensuremath{\mathit{n}}-1]}}$. Initially, this method is invoked with the arguments $ \ensuremath{\mathrm{quick\_sort}(\ensuremath{\mathit{a}},0,\mathrm{length}(\ensuremath{\mathit{a}}),c})$.

At the heart of the quicksort algorithm is the in-place partitioning algorithm. This algorithm, without using any extra space, swaps elements in $ \ensuremath{\ensuremath{\mathit{a}}}$ and computes indices $ \ensuremath{\ensuremath{\mathit{p}}}$ and $ \ensuremath{\ensuremath{\mathit{q}}}$ so that

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\math...
...it{i}}}} \le \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1$}
\end{cases}$

This partitioning, which is done by the $ {\color{black} \textbf{while}}$ loop in the code, works by iteratively increasing $ \ensuremath{\ensuremath{\mathit{p}}}$ and decreasing $ \ensuremath{\ensuremath{\mathit{q}}}$ while maintaining the first and last of these conditions. At each step, the element at position $ \ensuremath{\ensuremath{\mathit{j}}}$ is either moved to the front, left where it is, or moved to the back. In the first two cases, $ \ensuremath{\ensuremath{\mathit{j}}}$ is incremented, while in the last case, $ \ensuremath{\ensuremath{\mathit{j}}}$ is not incremented since the new element at position $ \ensuremath{\ensuremath{\mathit{j}}}$ has not yet been processed.

Quicksort is very closely related to the random binary search trees studied in Section 7.1. In fact, if the input to quicksort consists of $ \ensuremath{\ensuremath{\mathit{n}}}$ distinct elements, then the quicksort recursion tree is a random binary search tree. To see this, recall that when constructing a random binary search tree the first thing we do is pick a random element $ \ensuremath{\ensuremath{\mathit{x}}}$ and make it the root of the tree. After this, every element will eventually be compared to $ \ensuremath{\ensuremath{\mathit{x}}}$, with smaller elements going into the left subtree and larger elements into the right.

In quicksort, we select a random element $ \ensuremath{\ensuremath{\mathit{x}}}$ and immediately compare everything to $ \ensuremath{\ensuremath{\mathit{x}}}$, putting the smaller elements at the beginning of the array and larger elements at the end of the array. Quicksort then recursively sorts the beginning of the array and the end of the array, while the random binary search tree recursively inserts smaller elements in the left subtree of the root and larger elements in the right subtree of the root.

The above correspondence between random binary search trees and quicksort means that we can translate Lemma 7.1 to a statement about quicksort:

Lemma 11..1   When quicksort is called to sort an array containing the integers $ 0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1$, the expected number of times element $ \ensuremath{\ensuremath{\mathit{i}}}$ is compared to a pivot element is at most $ H_{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+1} + H_{\ensuremath{\ensu...
...th{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}}$.

A little summing up of harmonic numbers gives us the following theorem about the running time of quicksort:

Theorem 11..2   When quicksort is called to sort an array containing $ \ensuremath{\ensuremath{\mathit{n}}}$ distinct elements, the expected number of comparisons performed is at most $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\ln \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} + O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$.

Proof. Let $ T$ be the number of comparisons performed by quicksort when sorting $ \ensuremath{\ensuremath{\mathit{n}}}$ distinct elements. Using Lemma 11.1 and linearity of expectation, we have:

$\displaystyle \mathrm{E}[T]$ $\displaystyle = \sum_{i=0}^{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1...
...h{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}})$    
  $\displaystyle = 2\sum_{i=1}^{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}H_i$    
  $\displaystyle \le 2\sum_{i=1}^{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}H_{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}$    
  $\displaystyle \le 2\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\ln\ensurem...
...h{\mathit{n}}}} + O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}) \qedhere$    

$ \qedsymbol$

Theorem 11.3 describes the case where the elements being sorted are all distinct. When the input array, $ \ensuremath{\ensuremath{\mathit{a}}}$, contains duplicate elements, the expected running time of quicksort is no worse, and can be even better; any time a duplicate element $ \ensuremath{\ensuremath{\mathit{x}}}$ is chosen as a pivot, all occurrences of $ \ensuremath{\ensuremath{\mathit{x}}}$ get grouped together and do not take part in either of the two subproblems.

Theorem 11..3   The $ \ensuremath{\mathrm{quick\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{c}})}$ method runs in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time and the expected number of comparisons it performs is at most $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\ln \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} +O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$.


11.1.3 Heap-sort

The heap-sort algorithm is another in-place sorting algorithm. Heap-sort uses the binary heaps discussed in Section 10.1. Recall that the BinaryHeap data structure represents a heap using a single array. The heap-sort algorithm converts the input array $ \ensuremath{\ensuremath{\mathit{a}}}$ into a heap and then repeatedly extracts the minimum value.

More specifically, a heap stores $ \ensuremath{\ensuremath{\mathit{n}}}$ elements in an array, $ \ensuremath{\ensuremath{\mathit{a}}}$, at array locations $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[0]}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-1]}}$ with the smallest value stored at the root, $ \ensuremath{\ensuremath{\mathit{a}}[0]}$. After transforming $ \ensuremath{\ensuremath{\mathit{a}}}$ into a BinaryHeap, the heap-sort algorithm repeatedly swaps $ \ensuremath{\ensuremath{\mathit{a}}[0]}$ and $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-1]}$, decrements $ \ensuremath{\ensuremath{\mathit{n}}}$, and calls $ \ensuremath{\mathrm{trickle\_down}(0)}$ so that $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[0]}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-2]}}$ once again are a valid heap representation. When this process ends (because $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}=0$) the elements of $ \ensuremath{\ensuremath{\mathit{a}}}$ are stored in decreasing order, so $ \ensuremath{\ensuremath{\mathit{a}}}$ is reversed to obtain the final sorted order.11.1Figure 11.4 shows an example of the execution of $ \ensuremath{\mathrm{heap\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{c}})}$.

Figure 11.4: A snapshot of the execution of $ \ensuremath{\mathrm{heap\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{c}})}$. The shaded part of the array is already sorted. The unshaded part is a BinaryHeap. During the next iteration, element $ 5$ will be placed into array location $ 8$.
\includegraphics[scale=0.90909]{figs-python/heapsort}


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{heap\_sort}(...
...math{\ensuremath{\mathit{a}}.\mathrm{reverse}()}\\
\end{flushleft}\end{leftbar}

A key subroutine in heap sort is the constructor for turning an unsorted array $ \ensuremath{\ensuremath{\mathit{a}}}$ into a heap. It would be easy to do this in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time by repeatedly calling the BinaryHeap $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ method, but we can do better by using a bottom-up algorithm. Recall that, in a binary heap, the children of $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$ are stored at positions $ \ensuremath{\ensuremath{\mathit{a}}[2i+1]}$ and $ \ensuremath{\ensuremath{\mathit{a}}[2i+2]}$. This implies that the elements $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}}}[\lfloor\ensuremath{\ensurema...
...ts,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-1]}}$ have no children. In other words, each of $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}}}[\lfloor\ensuremath{\ensurema...
...ts,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-1]}}$ is a sub-heap of size 1. Now, working backwards, we can call $ \ensuremath{\mathrm{trickle\_down}(\ensuremath{\mathit{i}})}$ for each $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\in\{\lfloor \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2\rfloor-1,\ldots,0\}$. This works, because by the time we call $ \ensuremath{\mathrm{trickle\_down}(\ensuremath{\mathit{i}})}$, each of the two children of $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$ are the root of a sub-heap, so calling $ \ensuremath{\mathrm{trickle\_down}(\ensuremath{\mathit{i}})}$ makes $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$ into the root of its own subheap.

The interesting thing about this bottom-up strategy is that it is more efficient than calling $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ $ \ensuremath{\ensuremath{\mathit{n}}}$ times. To see this, notice that, for $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2$ elements, we do no work at all, for $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/4$ elements, we call $ \ensuremath{\mathrm{trickle\_down}(\ensuremath{\mathit{i}})}$ on a subheap rooted at $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$ and whose height is one, for $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/8$ elements, we call $ \ensuremath{\mathrm{trickle\_down}(\ensuremath{\mathit{i}})}$ on a subheap whose height is two, and so on. Since the work done by $ \ensuremath{\mathrm{trickle\_down}(\ensuremath{\mathit{i}})}$ is proportional to the height of the sub-heap rooted at $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$, this means that the total work done is at most

$\displaystyle \sum_{i=1}^{\log\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}...
...athit{n}}}}) = O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}) \enspace .
$

The second-last equality follows by recognizing that the sum $ \sum_{i=1}^{\infty} i/2^{i}$ is equal, by definition of expected value, to the expected number of times we toss a coin up to and including the first time the coin comes up as heads and applying Lemma 4.2.

The following theorem describes the performance of $ \ensuremath{\mathrm{heap\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{c}})}$.

Theorem 11..4   The $ \ensuremath{\mathrm{heap\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{c}})}$ method runs in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time and performs at most $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} + O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ comparisons.

Proof. The algorithm runs in three steps: (1) transforming $ \ensuremath{\ensuremath{\mathit{a}}}$ into a heap, (2) repeatedly extracting the minimum element from $ \ensuremath{\ensuremath{\mathit{a}}}$, and (3) reversing the elements in $ \ensuremath{\ensuremath{\mathit{a}}}$. We have just argued that step 1 takes $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time and performs $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ comparisons. Step 3 takes $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time and performs no comparisons. Step 2 performs $ \ensuremath{\ensuremath{\mathit{n}}}$ calls to $ \ensuremath{\mathrm{trickle\_down}(0)}$. The $ i$th such call operates on a heap of size $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-i$ and performs at most $ 2\log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-i)$ comparisons. Summing this over $ i$ gives

$\displaystyle \sum_{i=0}^{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-i} ...
...ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}
$

Adding the number of comparisons performed in each of the three steps completes the proof. $ \qedsymbol$

11.1.4 A Lower-Bound for Comparison-Based Sorting

We have now seen three comparison-based sorting algorithms that each run in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time. By now, we should be wondering if faster algorithms exist. The short answer to this question is no. If the only operations allowed on the elements of $ \ensuremath{\ensuremath{\mathit{a}}}$ are comparisons, then no algorithm can avoid doing roughly $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ comparisons. This is not difficult to prove, but requires a little imagination. Ultimately, it follows from the fact that

$\displaystyle \log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!)
= \log...
...athit{n}}}} - O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})
\enspace .
$

(Proving this fact is left as Exercise 11.10.)

We will start by focusing our attention on deterministic algorithms like merge-sort and heap-sort and on a particular fixed value of $ \ensuremath{\ensuremath{\mathit{n}}}$. Imagine such an algorithm is being used to sort $ \ensuremath{\ensuremath{\mathit{n}}}$ distinct elements. The key to proving the lower-bound is to observe that, for a deterministic algorithm with a fixed value of $ \ensuremath{\ensuremath{\mathit{n}}}$, the first pair of elements that are compared is always the same. For example, in $ \ensuremath{\mathrm{heap\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{c}})}$, when $ \ensuremath{\ensuremath{\mathit{n}}}$ is even, the first call to $ \ensuremath{\mathrm{trickle\_down}(\ensuremath{\mathit{i}})}$ is with $ \ensuremath{\ensuremath{\mathit{i}}\gets \ensuremath{\ensuremath{\mathit{n}}/2-1}}$ and the first comparison is between elements $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}/2-1]}$ and $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{n}}-1]}$.

Since all input elements are distinct, this first comparison has only two possible outcomes. The second comparison done by the algorithm may depend on the outcome of the first comparison. The third comparison may depend on the results of the first two, and so on. In this way, any deterministic comparison-based sorting algorithm can be viewed as a rooted binary comparison tree. Each internal node, $ \ensuremath{\ensuremath{\mathit{u}}}$, of this tree is labelled with a pair of indices $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{i}}}$ and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{j}}}$. If $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{u}}.\ensur...
...math{\ensuremath{\mathit{a}}[\ensuremath{\mathit{u}}.\ensuremath{\mathit{j}}]}}$ the algorithm proceeds to the left subtree, otherwise it proceeds to the right subtree. Each leaf $ \ensuremath{\ensuremath{\mathit{w}}}$ of this tree is labelled with a permutation $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{p}}[0]}},\...
...th{\ensuremath{\mathit{w}}.\ensuremath{\mathit{p}}[\ensuremath{\mathit{n}}-1]}}$ of $ 0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1$. This permutation represents the one that is required to sort $ \ensuremath{\ensuremath{\mathit{a}}}$ if the comparison tree reaches this leaf. That is,

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\math...
...h{\mathit{w}}.\ensuremath{\mathit{p}}[\ensuremath{\mathit{n}}-1]}]} \enspace .
$

An example of a comparison tree for an array of size $ \ensuremath{\ensuremath{\mathit{n}}\gets \ensuremath{3}}$ is shown in Figure 11.5.
Figure 11.5: A comparison tree for sorting an array $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[0]}},\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[1]}},\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[2]}}$ of length $ \ensuremath{\ensuremath{\mathit{n}}\gets \ensuremath{3}}$.
\includegraphics[width=\textwidth ]{figs-python/comparison-tree}

The comparison tree for a sorting algorithm tells us everything about the algorithm. It tells us exactly the sequence of comparisons that will be performed for any input array, $ \ensuremath{\ensuremath{\mathit{a}}}$, having $ \ensuremath{\ensuremath{\mathit{n}}}$ distinct elements and it tells us how the algorithm will reorder $ \ensuremath{\ensuremath{\mathit{a}}}$ in order to sort it. Consequently, the comparison tree must have at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!$ leaves; if not, then there are two distinct permutations that lead to the same leaf; therefore, the algorithm does not correctly sort at least one of these permutations.

For example, the comparison tree in Figure 11.6 has only $ 4< 3!=6$ leaves. Inspecting this tree, we see that the two input arrays $ 3,1,2$ and $ 3,2,1$ both lead to the rightmost leaf. On the input $ 3,1,2$ this leaf correctly outputs $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[1]}}=1,\ensuremath{\ensuremath...
...emath{\mathit{a}}[2]}}=2,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[0]}}=3$. However, on the input $ 3,2,1$, this node incorrectly outputs $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}[1]}}=2,\ensuremath{\ensuremath...
...emath{\mathit{a}}[2]}}=1,\ensuremath{\ensuremath{\ensuremath{\mathit{a}}[0]}}=3$. This discussion leads to the primary lower-bound for comparison-based algorithms.

Figure 11.6: A comparison tree that does not correctly sort every input permutation.
\includegraphics[width=\textwidth ]{figs-python/comparison-tree-b}

Theorem 11..5   For any deterministic comparison-based sorting algorithm $ \mathcal{A}$ and any integer $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\ge 1$, there exists an input array $ \ensuremath{\ensuremath{\mathit{a}}}$ of length $ \ensuremath{\ensuremath{\mathit{n}}}$ such that $ \mathcal{A}$ performs at least $ \log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!) =
\ensuremath{\ensur...
...{\ensuremath{\mathit{n}}}}-O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ comparisons when sorting $ \ensuremath{\ensuremath{\mathit{a}}}$.

Proof. By the preceding discussion, the comparison tree defined by $ \mathcal{A}$ must have at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!$ leaves. An easy inductive proof shows that any binary tree with $ k$ leaves has a height of at least $ \log k$. Therefore, the comparison tree for $ \mathcal{A}$ has a leaf, $ \ensuremath{\ensuremath{\mathit{w}}}$, with a depth of at least $ \log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!)$ and there is an input array $ \ensuremath{\ensuremath{\mathit{a}}}$ that leads to this leaf. The input array $ \ensuremath{\ensuremath{\mathit{a}}}$ is an input for which $ \mathcal{A}$ does at least $ \log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!)$ comparisons. $ \qedsymbol$

Theorem 11.5 deals with deterministic algorithms like merge-sort and heap-sort, but doesn't tell us anything about randomized algorithms like quicksort. Could a randomized algorithm beat the $ \log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!)$ lower bound on the number of comparisons? The answer, again, is no. Again, the way to prove it is to think differently about what a randomized algorithm is.

In the following discussion, we will assume that our decision trees have been ``cleaned up'' in the following way: Any node that can not be reached by some input array $ \ensuremath{\ensuremath{\mathit{a}}}$ is removed. This cleaning up implies that the tree has exactly $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!$ leaves. It has at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!$ leaves because, otherwise, it could not sort correctly. It has at most $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!$ leaves since each of the possible $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!$ permutation of $ \ensuremath{\ensuremath{\mathit{n}}}$ distinct elements follows exactly one root to leaf path in the decision tree.

We can think of a randomized sorting algorithm, $ \mathcal{R}$, as a deterministic algorithm that takes two inputs: The input array $ \ensuremath{\ensuremath{\mathit{a}}}$ that should be sorted and a long sequence $ b=b_1,b_2,b_3,\ldots,b_m$ of random real numbers in the range $ [0,1]$. The random numbers provide the randomization for the algorithm. When the algorithm wants to toss a coin or make a random choice, it does so by using some element from $ b$. For example, to compute the index of the first pivot in quicksort, the algorithm could use the formula $ \lfloor n b_1\rfloor$.

Now, notice that if we fix $ b$ to some particular sequence $ \hat{b}$ then $ \mathcal{R}$ becomes a deterministic sorting algorithm, $ \mathcal{R}(\hat{b})$, that has an associated comparison tree, $ \mathcal{T}(\hat{b})$. Next, notice that if we select $ \ensuremath{\ensuremath{\mathit{a}}}$ to be a random permutation of $ \{1,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\}$, then this is equivalent to selecting a random leaf, $ \ensuremath{\ensuremath{\mathit{w}}}$, from the $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!$ leaves of $ \mathcal{T}(\hat{b})$.

Exercise 11.12 asks you to prove that, if we select a random leaf from any binary tree with $ k$ leaves, then the expected depth of that leaf is at least $ \log k$. Therefore, the expected number of comparisons performed by the (deterministic) algorithm $ \mathcal{R}(\hat{b})$ when given an input array containing a random permutation of $ \{1,\ldots,n\}$ is at least $ \log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!)$. Finally, notice that this is true for every choice of $ \hat{b}$, therefore it holds even for $ \mathcal{R}$. This completes the proof of the lower-bound for randomized algorithms.

Theorem 11..6   For any integer $ n\ge 1$ and any (deterministic or randomized) comparison-based sorting algorithm $ \mathcal{A}$, the expected number of comparisons done by $ \mathcal{A}$ when sorting a random permutation of $ \{1,\ldots,n\}$ is at least $ \log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!) = \ensuremath{\ensure...
...{\ensuremath{\mathit{n}}}}-O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$.



Footnotes

... order.11.1
The algorithm could alternatively redefine the $ \ensuremath{\mathrm{compare}(\ensuremath{\mathit{x}},\ensuremath{\mathit{y}})}$ function so that the heap sort algorithm stores the elements directly in ascending order.
opendatastructures.org

12 . 2 AdjacencyLists: A Graph as a Collection of Lists

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.


12.2 AdjacencyLists: A Graph as a Collection of Lists

Adjacency list representations of graphs take a more vertex-centric approach. There are many possible implementations of adjacency lists. In this section, we present a simple one. At the end of the section, we discuss different possibilities. In an adjacency list representation, the graph $ G=(V,E)$ is represented as an array, $ \ensuremath{\ensuremath{\mathit{adj}}}$, of lists. The list $ \ensuremath{\ensuremath{\mathit{adj}}[\ensuremath{\mathit{i}}]}$ contains a list of all the vertices adjacent to vertex $ \ensuremath{\ensuremath{\mathit{i}}}$. That is, it contains every index $ \ensuremath{\ensuremath{\mathit{j}}}$ such that $ \ensuremath{\ensuremath{(\ensuremath{\mathit{i}},\ensuremath{\mathit{j}})}}\in E$.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{initialize}(...
...ets \ensuremath{\mathrm{\mathrm{ArrayStack}}()}}\\
\end{flushleft}\end{leftbar}
(An example is shown in Figure 12.3.) In this particular implementation, we represent each list in $ \ensuremath{\ensuremath{\mathit{adj}}}$ as ArrayStack, because we would like constant time access by position. Other options are also possible. Specifically, we could have implemented $ \ensuremath{\ensuremath{\mathit{adj}}}$ as a DLList.

Figure 12.3: A graph and its adjacency lists
\includegraphics[scale=0.90909]{figs-python/graph}



0 1 2 3 4 5 6 7 8 9 10 11  
1 0 1 2 0 1 5 6 4 8 9 10  
4 2 3 7 5 2 2 3 9 5 6 7  
  6 6   8 6 7 11   10 11    
  5       9 10            
          4              

The $ \ensuremath{\mathrm{add\_edge}(\ensuremath{\mathit{i}},\ensuremath{\mathit{j}})}$ operation just appends the value $ \ensuremath{\ensuremath{\mathit{j}}}$ to the list $ \ensuremath{\ensuremath{\mathit{adj}}[\ensuremath{\mathit{i}}]}$:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add\_edge}(\...
...t{i}}].\mathrm{append}(\ensuremath{\mathit{j}})}\\
\end{flushleft}\end{leftbar}
This takes constant time.

The $ \ensuremath{\mathrm{remove\_edge}(\ensuremath{\mathit{i}},\ensuremath{\mathit{j}})}$ operation searches through the list $ \ensuremath{\ensuremath{\mathit{adj}}[\ensuremath{\mathit{i}}]}$ until it finds $ \ensuremath{\ensuremath{\mathit{j}}}$ and then removes it:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove\_edge...
...m} \hspace*{1em} {\color{black} \textbf{return}}\\
\end{flushleft}\end{leftbar}
This takes $ O(\deg(\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}))$ time, where $ \deg(\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}})$ (the degree of $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}$) counts the number of edges in $ E$ that have $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}$ as their source.

The $ \ensuremath{\mathrm{has\_edge}(\ensuremath{\mathit{i}},\ensuremath{\mathit{j}})}$ operation is similar; it searches through the list $ \ensuremath{\ensuremath{\mathit{adj}}[\ensuremath{\mathit{i}}]}$ until it finds $ \ensuremath{\ensuremath{\mathit{j}}}$ (and returns true), or reaches the end of the list (and returns false):
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{has\_edge}(\...
...eturn}} \ensuremath{\ensuremath{\mathit{false}}}\\
\end{flushleft}\end{leftbar}
This also takes $ O(\deg(\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}))$ time.

The $ \ensuremath{\mathrm{out\_edges}(\ensuremath{\mathit{i}})}$ operation is very simple; it returns the list $ \ensuremath{\ensuremath{\mathit{adj}}[\ensuremath{\mathit{i}}]}$ :
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{out\_edges}(...
...suremath{\mathit{adj}}[\ensuremath{\mathit{i}}]}\\
\end{flushleft}\end{leftbar}

The $ \ensuremath{\mathrm{in\_edges}(\ensuremath{\mathit{i}})}$ operation is much more work. It scans over every vertex $ j$ checking if the edge $ \ensuremath{(\ensuremath{\mathit{i}},\ensuremath{\mathit{j}})}$ exists and, if so, adding $ \ensuremath{\ensuremath{\mathit{j}}}$ to the output list:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{in\_edges}(\...
...{return}} \ensuremath{\ensuremath{\mathit{out}}}\\
\end{flushleft}\end{leftbar}
This operation is very slow. It scans the adjacency list of every vertex, so it takes $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} + \ensuremath{\ensuremath{\ensuremath{\mathit{m}}}})$ time.

The following theorem summarizes the performance of the above data structure:

Theorem 12..2   The AdjacencyLists data structure implements the Graph interface. An AdjacencyLists supports the operations
  • $ \ensuremath{\mathrm{add\_edge}(\ensuremath{\mathit{i}},\ensuremath{\mathit{j}})}$ in constant time per operation;
  • $ \ensuremath{\mathrm{remove\_edge}(\ensuremath{\mathit{i}},\ensuremath{\mathit{j}})}$ and $ \ensuremath{\mathrm{has\_edge}(\ensuremath{\mathit{i}},\ensuremath{\mathit{j}})}$ in $ O(\deg(\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}))$ time per operation;
  • $ \ensuremath{\mathrm{in\_edges}(\ensuremath{\mathit{i}})}$ in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{m}}}})$ time per operation.
The space used by a AdjacencyLists is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{m}}}})$.

As alluded to earlier, there are many different choices to be made when implementing a graph as an adjacency list. Some questions that come up include:

Most of these questions come down to a tradeoff between complexity (and space) of implementation and performance features of the implementation.

opendatastructures.org

Responsive web design

Assigned source reading · Mozilla Contributors

MDN Web Docs — Mozilla Contributors

Original source · Creative Commons Attribution-ShareAlike 2.5 or later · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Responsive web design

Responsive web design (RWD) is a web design approach to make web pages render well on all screen sizes and resolutions while ensuring good usability. It is the way to design for a multi-device web. In this article, we'll help you understand some techniques that can be used to master it.

Prerequisites: Structuring content with HTML, CSS Styling basics, Fundamental text and font styling, familiarity with CSS layout fundamental concepts.
Learning outcomes:
  • What responsive design is — designing web layouts so that they are flexible and work well across different device screen sizes, resolutions, etc.
  • The relationship between modern layout tools such as grid and flexbox, and responsive design.
  • The concepts behind using media queries for responsive design, including mobile-first and breakpoints.
  • Why <meta viewport=""> is needed to get web documents to display appropriately on mobile devices.

Precursor to responsive design: mobile web design

Before responsive web design became the standard approach for making websites work across different device types, web developers used to talk about mobile web design, mobile web development, or sometimes, mobile-friendly design. These are basically the same as responsive web design — the goals are to make sure that websites work well across devices with different physical attributes (screen size, resolution) in terms of layout, content (text and media), and performance.

The difference is mainly to do with the devices involved, and the technologies available to create solutions:

  • We used to talk about desktop or mobile, but now there are many different types of device available such as desktop, laptop, mobile, tablets, watches, etc. Instead of catering for a few different screen sizes, we now need to design sites defensively to cater for common screen sizes and resolutions, plus unknowns.
  • Mobile devices used to be low-powered in terms of CPU/GPU and available bandwidth. Some didn't support CSS or even HTML, and as a result, it was common to perform server-side browser sniffing to determine device/browser type before then serving a site that the device would be able to cope with. Mobile devices often had really simple, basic experiences served to them because it was all they could handle. These days, mobile devices are able to handle the same technologies as desktop computers, so such techniques are less common.
    • You should still use the techniques discussed in this article to serve mobile users a suitable experience, as there are still constraints such as battery life and bandwidth to worry about.
    • User experience is still a concern. A mobile user of a travel site might just want to check flight times and delay information, for example, and not be presented with a 3D animated globe showing flight paths and your company history.
  • Modern technologies are much better for creating responsive experiences. For example, responsive images/media technologies now allow appropriate media to be served to different devices without having to rely on techniques like server-side sniffing.

Introducing responsive web design

HTML is fundamentally responsive, or fluid. If you create a web page containing only HTML, with no CSS, and resize the window, the browser will automatically reflow the text to fit the viewport.

While the default responsive behavior may sound like no solution is needed, long lines of text displayed full screen on a wide monitor can be difficult to read. This problem can be solved with CSS, for example by creating narrow columns to limit the line length. However, this can create new problems for users that narrow their browser window or view the site on a mobile device — the columns will look squashed and become harder to read.

A layout with two columns squashed into a mobile size viewport.

Creating a non-resizable web page by setting a fixed width doesn't work either; that leads to scroll bars on narrow devices and too much empty space on wide screens.

Responsive web design, or RWD, is a design approach that addresses the full range of available devices and device sizes, enabling automatic adaption to the screen, whether the content is viewed on a tablet, phone, television, or watch.

Responsive web design isn't a separate technology — it is an approach. It is a term used to describe a set of best practices used to create a layout that can respond to any device being used to view the content.

The term responsive design, coined by Ethan Marcotte in 2010, described using fluid grids, fluid images, and media queries to create responsive content.

At the time, the recommendation was to use CSS float for layout and media queries to query the browser width, creating layouts for different breakpoints. Fluid images are set to not exceed the width of their container; they have their max-width property set to 100%. Fluid images scale down when their containing column narrows but do not grow larger than their intrinsic size when the column grows. This enables an image to scale down to fit its content, rather than overflow it, but not grow larger and become pixelated if the container becomes wider than the image.

Modern CSS layout methods are inherently responsive, and, since the publication of Marcotte's article, we have a multitude of features built into the web platform to make designing responsive sites easier.

The rest of this article will explain the various web platform features you might want to use when creating a responsive site.

Media Queries

Media queries allow us to run a series of tests (for example, whether the user's screen is greater than a certain width or resolution) and apply CSS selectively to style the page appropriately for the user's needs.

For example, the following media query tests to see if the current web page is being displayed as screen media (therefore not a printed document) and the viewport is at least 80rem wide. The .container rule will only be applied if these two things are true.

css
@media screen and (width >= 80rem) {
  .container {
    margin: 1em 2em;
  }
}

You can add multiple media queries within a stylesheet, tweaking your whole layout or parts of it to best suit the various screen sizes. The points at which a media query is introduced, and the layout changes, are known as breakpoints.

A common approach when using media queries is to create a simple single-column layout for narrow-screen devices (for example, mobile phones), then check for wider screens and implement a multiple-column layout when you know that you have enough screen width to handle it. Designing for mobile first is known as mobile first design.

If using breakpoints, best practices encourage defining media query breakpoints with relative units rather than absolute sizes of an individual device.

There are different approaches to the styles defined within a media query block; ranging from using media queries to <link> style sheets based on browser size ranges to only including custom properties variables to store values associated with each breakpoint.

Media queries can help with RWD, but are not a requirement. Flexible grids, relative units, and minimum and maximum unit values can be used without media queries.

Note: Scrimba has a tutorial called Aside: Media queries MDN learning partner, which provides an interactive introduction to media queries plus a challenge to test that you understand the basics.

Responsive layout technologies

Responsive sites are built on flexible grids, meaning you don't need to target every possible device size with pixel perfect layouts.

By using a flexible grid, you can change a feature or add in a breakpoint and change the design at the point where the content starts to look bad. For example, to ensure line lengths don't become unreadably long as the screen size increases you can use columns; if a box becomes squashed with two words on each line as it narrows you can set a breakpoint.

Several layout methods — including Flexbox, and CSS Grid — are responsive by default. They all assume that you are trying to create a flexible grid and give you easier ways to do so.

Flexbox

In flexbox, flex items shrink or grow, distributing space between the items according to the space in their container. By changing the values for flex-grow and flex-shrink you can indicate how you want the items to behave when they encounter more or less space around them.

In the example below the flex items will each take an equal amount of space in the flex container, using the shorthand of flex: 1 as previously discussed (see Flexbox: Flexible sizing of flex items).

css
.container {
  display: flex;
}

.item {
  flex: 1;
}

Here's how we could use flexbox with a media query for responsive design.

html
<div class="wrapper">
  <div class="col1">
    <p>
      This layout is responsive. See what happens if you make the browser window
      wider or narrow.
    </p>
  </div>
  <div class="col2">
    <p>
      One November night in the year 1782, so the story runs, two brothers sat
      over their winter fire in the little French town of Annonay, watching the
      grey smoke-wreaths from the hearth curl up the wide chimney. Their names
      were Stephen and Joseph Montgolfier, they were papermakers by trade, and
      were noted as possessing thoughtful minds and a deep interest in all
      scientific knowledge and new discovery.
    </p>
    <p>
      Before that night—a memorable night, as it was to prove—hundreds of
      millions of people had watched the rising smoke-wreaths of their fires
      without drawing any special inspiration from the fact.
    </p>
  </div>
</div>
css
@media screen and (width >= 600px) {
  .wrapper {
    display: flex;
  }

  .col1 {
    flex: 1;
    margin-right: 5%;
  }

  .col2 {
    flex: 2;
  }
}

Resize your browser window. The layout will change between a single-column and a two-column layout when the size of the above example crosses the 600px width threshold.

CSS grid

In CSS grid layout the fr unit allows the distribution of available space across grid tracks. The next example creates a grid container with three tracks sized at 1fr. This will create three column tracks, each taking one part of the available space in the container. You already looked at this approach (see Flexible grids with the fr unit for a recap).

css
.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

Here's how we could use grid layout with a media query for responsive design.

html
<div class="wrapper">
  <div class="col1">
    <p>
      This layout is responsive. See what happens if you make the browser window
      wider or narrow.
    </p>
  </div>
  <div class="col2">
    <p>
      One November night in the year 1782, so the story runs, two brothers sat
      over their winter fire in the little French town of Annonay, watching the
      grey smoke-wreaths from the hearth curl up the wide chimney. Their names
      were Stephen and Joseph Montgolfier, they were papermakers by trade, and
      were noted as possessing thoughtful minds and a deep interest in all
      scientific knowledge and new discovery.
    </p>
    <p>
      Before that night—a memorable night, as it was to prove—hundreds of
      millions of people had watched the rising smoke-wreaths of their fires
      without drawing any special inspiration from the fact.
    </p>
  </div>
</div>
css
@media screen and (width >= 600px) {
  .wrapper {
    display: grid;
    grid-template-columns: 1fr 2fr;
    column-gap: 5%;
  }
}

Again, try resizing your browser window — you should see the example layout change at the 600px width threshold, in the same way as the previous example.

Responsive images/media

To ensure media is never larger than its responsive container, the following approach can be used:

css
img,
picture,
video {
  max-width: 100%;
}

This scales media elements to ensure they never overflow their containers.

Note: Using a single large image and scaling it down to fit small devices wastes bandwidth by downloading images larger than required. It can also look bad — a landscape image for example might look good on a widescreen monitor, but it might be hard to see on a mobile device, which would suit a portrait image better. Such problems can be solved using the <picture> element and the <img> srcset and sizes attributes. These are advanced features that are beyond the scope of this course, but you can find a detailed guide at Responsive images.

Other useful tips:

  • Always make sure to use an appropriate image format for your website images (such as PNG or JPG), and make sure to optimize the file size using a graphics editor before you put them on your website.
  • You can make use of CSS features like gradients and shadows to implement visual effects without using images.
  • You can use media queries inside the media attribute on <source> elements nested inside <video>/<audio> elements to serve video/audio files as appropriate for different devices (responsive video/audio).

Responsive typography

Responsive typography describes changing font sizes within media queries or using viewport units to reflect lesser or greater amounts of screen real estate.

Using media queries for responsive typography

In this example, we want to set our level 1 heading to be 4rem, meaning it will be four times our base font size. That's a really large heading! We only want this jumbo heading on larger screen sizes, therefore we first give the heading a smaller size of 2rem, then use media queries to overwrite it with the larger size if we know that the user has a screen width of at least 1200px.

css
html {
  font-size: 1em;
}

h1 {
  font-size: 2rem;
}

@media (width >= 1200px) {
  h1 {
    font-size: 4rem;
  }
}

The next example is a modified version of our earlier responsive grid example, which includes a responsive heading using the method outlined. On mobile the heading is smaller, but on desktop, we see the larger heading size:

html
<div class="wrapper">
  <div class="col1">
    <h1>Watch my size!</h1>
    <p>
      This layout is responsive. See what happens if you make the browser window
      wider or narrow.
    </p>
  </div>
  <div class="col2">
    <p>
      One November night in the year 1782, so the story runs, two brothers sat
      over their winter fire in the little French town of Annonay, watching the
      grey smoke-wreaths from the hearth curl up the wide chimney. Their names
      were Stephen and Joseph Montgolfier, they were papermakers by trade, and
      were noted as possessing thoughtful minds and a deep interest in all
      scientific knowledge and new discovery.
    </p>
    <p>
      Before that night—a memorable night, as it was to prove—hundreds of
      millions of people had watched the rising smoke-wreaths of their fires
      without drawing any special inspiration from the fact.
    </p>
  </div>
</div>
css
html {
  font-size: 1em;
}

body {
  font:
    1.2em "Helvetica",
    "Arial",
    sans-serif;
  margin: 20px;
  padding: 0;
  background-color: #eeeeee;
}
.wrapper {
  max-width: 960px;
  margin: 2em auto;
}

h1 {
  font-size: 2rem;
  margin: 0;
}

.col1,
.col2 {
  background-color: white;
}

@media screen and (width >= 600px) {
  .wrapper {
    display: grid;
    grid-template-columns: 1fr 2fr;
    column-gap: 5%;
  }

  h1 {
    font-size: 4rem;
  }
}

As with previous examples, try changing the browser window width, and note how not only the layout changes at the 600px width threshold, but also the heading size.

As this approach to typography shows, you do not need to restrict media queries to only changing the layout of the page. They can be used to tweak any element to make it more usable or attractive at alternate screen sizes.

Using viewport units for responsive typography

Viewport units vw can also be used to enable responsive typography, without the need for setting breakpoints with media queries. 1vw is equal to one percent of the viewport width, meaning that if you set your font size using vw, it will always relate to the size of the viewport.

css
h1 {
  font-size: 6vw;
}

The problem with doing the above is that the user loses the ability to zoom any text set using the vw unit, as that text is always related to the size of the viewport. Therefore you should never set text using viewport units alone.

There is a solution, and it involves using calc(). If you add the vw unit to a value set using a fixed size such as ems or rems then the text will still be zoomable. Essentially, the vw unit adds on top of that zoomed value:

css
h1 {
  font-size: calc(1.5rem + 4vw);
}

This means that we only need to specify the font size for the heading once, rather than set it up for mobile and redefine it in the media queries. The font then gradually increases as you increase the size of the viewport.

html
<div class="wrapper">
  <div class="col1">
    <h1>Watch my size!</h1>
    <p>
      This layout is responsive. See what happens if you make the browser window
      wider or narrow.
    </p>
  </div>
  <div class="col2">
    <p>
      One November night in the year 1782, so the story runs, two brothers sat
      over their winter fire in the little French town of Annonay, watching the
      grey smoke-wreaths from the hearth curl up the wide chimney. Their names
      were Stephen and Joseph Montgolfier, they were papermakers by trade, and
      were noted as possessing thoughtful minds and a deep interest in all
      scientific knowledge and new discovery.
    </p>
  </div>
</div>
css
body {
  font: 1.2em / 1.5 sans-serif;
  margin: 20px;
  padding: 0;
  background-color: #eeeeee;
}

.wrapper {
  max-width: 960px;
  margin: 2em auto;
}

h1 {
  font-size: calc(1.5rem + 4vw);
  margin: 0;
}

.col1,
.col2 {
  background-color: white;
}

@media screen and (width >= 600px) {
  .wrapper {
    display: grid;
    grid-template-columns: 1fr 2fr;
    column-gap: 5%;
  }
}

Try resizing the browser window, as before, and note how this time the heading size increases gradually as the width changes.

The viewport meta tag

If you look at the HTML source of a responsive page, you will usually see the following <meta> tag in the <head> of the document.

html
<meta name="viewport" content="width=device-width" />

This viewport meta tag tells mobile browsers that they should set the width of the viewport to the device's width which shows the document at the mobile-optimized size that you intended.

Why is this needed? Because mobile browsers tend to lie about their viewport width.

This meta tag exists because when smartphones first arrived, most sites were not mobile optimized. The mobile browser would, therefore, set the viewport width to 980 pixels, render the page at that width, and show the result as a zoomed-out version of the desktop layout. Users could zoom in and pan around the website to view the bits they were interested in, but it looked bad.

By setting width=device-width you are overriding a mobile device's default, like the iPhone's default width=980px, with the actual width of the device. Without it, your responsive design with breakpoints and media queries may not work as intended on mobile browsers. If you've got a narrow screen layout that kicks in at 480px viewport width or less, but the device is saying it is 980px wide, that user will not see your narrow screen layout.

So you should always include the viewport meta tag in the head of your documents.

There are a number of other options you can put inside the content attribute of the viewport meta tag — see the <meta name="viewport"> reference for more details.

Summary

Responsive design refers to a site or application design that responds to the environment in which it is viewed. It encompasses a number of CSS and HTML features and techniques and is essentially how we build websites by default. Consider the sites that you visit on your phone — it is probably fairly unusual to come across a site that is the desktop version scaled down, or where you need to scroll sideways to find things. This is because the web has moved to this approach of designing responsively.

It has also become much easier to achieve responsive designs with the help of the layout methods covered in this article. If you are new to web development today you have many more tools at your disposal than in the early days of responsive design. It is therefore worth checking the age of any materials you are using. While the historical articles are still useful, modern use of CSS and HTML makes it far easier to create elegant and useful designs, no matter what device your visitor views the site with.

Next, we will study media queries in more detail and show how to use them to solve some common problems.

See also

  • Working with touchscreen devices:
    • Touch events provide the ability to interpret finger (or stylus) activity on touch screens or trackpads, enabling quality support for complex touch-based user interfaces.
    • Use the pointer or any-pointer media queries to load different CSS on touch-enabled devices.
  • CSS-Tricks guide to media queries
  • The Frontend Developer Career Path MDN learning partner from Scrimba teaches all you need to know to be a competent front-end web developer, with fun interactive lessons and challenges, knowledgeable teachers, and a supportive community. Go from zero to landing your first front-end job! Many of the course components are available as standalone free versions. This includes a module on responsive design.

2.5. Querying a Table #

Assigned source reading · The PostgreSQL Global Development Group and The Regents of the University of California

Portions Copyright © 1996–2026 The PostgreSQL Global Development Group. Portions Copyright © 1994 The Regents of the University of California.

Original source · PostgreSQL License · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Full license and notices
License
PostgreSQL is released under the
PostgreSQL License
,
a liberal Open Source license, similar to the BSD or MIT licenses.
PostgreSQL Database Management System
(also known as Postgres, formerly as Postgres95)
Portions Copyright © 1996-2026, The PostgreSQL Global Development Group
Portions Copyright © 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its
  documentation for any purpose, without fee, and without a written agreement
  is hereby granted, provided that the above copyright notice and this
  paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
  DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
  LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
  DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
  ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
  PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Will PostgreSQL ever be released under a different license?
The PostgreSQL Global Development Group remains committed to making
  PostgreSQL available as free and open source software in perpetuity. There are
  no plans to change the PostgreSQL License or release PostgreSQL under a
  different license.
If you would like to read more about this topic, then please take a look at
  the
mailing list archives
at one of the many discussions
  on this subject.

2.5. Querying a Table #

To retrieve data from a table, the table is queried. An SQL SELECT statement is used to do this. The statement is divided into a select list (the part that lists the columns to be returned), a table list (the part that lists the tables from which to retrieve the data), and an optional qualification (the part that specifies any restrictions). For example, to retrieve all the rows of table weather, type:

SELECT * FROM weather;

Here * is a shorthand for “all columns”. [2] So the same result would be had with:

SELECT city, temp_lo, temp_hi, prcp, date FROM weather;

The output should be:

     city      | temp_lo | temp_hi | prcp |    date
---------------+---------+---------+------+------------
 San Francisco |      46 |      50 | 0.25 | 1994-11-27
 San Francisco |      43 |      57 |    0 | 1994-11-29
 Hayward       |      37 |      54 |      | 1994-11-29
(3 rows)

You can write expressions, not just simple column references, in the select list. For example, you can do:

SELECT city, (temp_hi+temp_lo)/2 AS temp_avg, date FROM weather;

This should give:

     city      | temp_avg |    date
---------------+----------+------------
 San Francisco |       48 | 1994-11-27
 San Francisco |       50 | 1994-11-29
 Hayward       |       45 | 1994-11-29
(3 rows)

Notice how the AS clause is used to relabel the output column. (The AS clause is optional.)

A query can be “qualified” by adding a WHERE clause that specifies which rows are wanted. The WHERE clause contains a Boolean (truth value) expression, and only rows for which the Boolean expression is true are returned. The usual Boolean operators (AND, OR, and NOT) are allowed in the qualification. For example, the following retrieves the weather of San Francisco on rainy days:

SELECT * FROM weather
    WHERE city = 'San Francisco' AND prcp > 0.0;

Result:

     city      | temp_lo | temp_hi | prcp |    date
---------------+---------+---------+------+------------
 San Francisco |      46 |      50 | 0.25 | 1994-11-27
(1 row)

You can request that the results of a query be returned in sorted order:

SELECT * FROM weather
    ORDER BY city;
     city      | temp_lo | temp_hi | prcp |    date
---------------+---------+---------+------+------------
 Hayward       |      37 |      54 |      | 1994-11-29
 San Francisco |      43 |      57 |    0 | 1994-11-29
 San Francisco |      46 |      50 | 0.25 | 1994-11-27

In this example, the sort order isn't fully specified, and so you might get the San Francisco rows in either order. But you'd always get the results shown above if you do:

SELECT * FROM weather
    ORDER BY city, temp_lo;

You can request that duplicate rows be removed from the result of a query:

SELECT DISTINCT city
    FROM weather;
     city
---------------
 Hayward
 San Francisco
(2 rows)

Here again, the result row ordering might vary. You can ensure consistent results by using DISTINCT and ORDER BY together: [3]

SELECT DISTINCT city
    FROM weather
    ORDER BY city;


[2] While SELECT * is useful for off-the-cuff queries, it is widely considered bad style in production code, since adding a column to the table would change the results.

[3] In some database systems, including older versions of PostgreSQL, the implementation of DISTINCT automatically orders the rows and so ORDER BY is unnecessary. But this is not required by the SQL standard, and current PostgreSQL does not guarantee that DISTINCT causes the rows to be ordered.

3.5. Window Functions #

Assigned source reading · The PostgreSQL Global Development Group and The Regents of the University of California

Portions Copyright © 1996–2026 The PostgreSQL Global Development Group. Portions Copyright © 1994 The Regents of the University of California.

Original source · PostgreSQL License · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Full license and notices
License
PostgreSQL is released under the
PostgreSQL License
,
a liberal Open Source license, similar to the BSD or MIT licenses.
PostgreSQL Database Management System
(also known as Postgres, formerly as Postgres95)
Portions Copyright © 1996-2026, The PostgreSQL Global Development Group
Portions Copyright © 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its
  documentation for any purpose, without fee, and without a written agreement
  is hereby granted, provided that the above copyright notice and this
  paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
  DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
  LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
  DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
  ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
  PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Will PostgreSQL ever be released under a different license?
The PostgreSQL Global Development Group remains committed to making
  PostgreSQL available as free and open source software in perpetuity. There are
  no plans to change the PostgreSQL License or release PostgreSQL under a
  different license.
If you would like to read more about this topic, then please take a look at
  the
mailing list archives
at one of the many discussions
  on this subject.

3.5. Window Functions #

A window function performs a calculation across a set of table rows that are somehow related to the current row. This is comparable to the type of calculation that can be done with an aggregate function. However, window functions do not cause rows to become grouped into a single output row like non-window aggregate calls would. Instead, the rows retain their separate identities. Behind the scenes, the window function is able to access more than just the current row of the query result.

Here is an example that shows how to compare each employee's salary with the average salary in his or her department:

SELECT depname, empno, salary, avg(salary) OVER (PARTITION BY depname) FROM empsalary;
  depname  | empno | salary |          avg
-----------+-------+--------+-----------------------
 develop   |    11 |   5200 | 5020.0000000000000000
 develop   |     7 |   4200 | 5020.0000000000000000
 develop   |     9 |   4500 | 5020.0000000000000000
 develop   |     8 |   6000 | 5020.0000000000000000
 develop   |    10 |   5200 | 5020.0000000000000000
 personnel |     5 |   3500 | 3700.0000000000000000
 personnel |     2 |   3900 | 3700.0000000000000000
 sales     |     3 |   4800 | 4866.6666666666666667
 sales     |     1 |   5000 | 4866.6666666666666667
 sales     |     4 |   4800 | 4866.6666666666666667
(10 rows)

The first three output columns come directly from the table empsalary, and there is one output row for each row in the table. The fourth column represents an average taken across all the table rows that have the same depname value as the current row. (This actually is the same function as the non-window avg aggregate, but the OVER clause causes it to be treated as a window function and computed across the window frame.)

A window function call always contains an OVER clause directly following the window function's name and argument(s). This is what syntactically distinguishes it from a normal function or non-window aggregate. The OVER clause determines exactly how the rows of the query are split up for processing by the window function. The PARTITION BY clause within OVER divides the rows into groups, or partitions, that share the same values of the PARTITION BY expression(s). For each row, the window function is computed across the rows that fall into the same partition as the current row.

You can also control the order in which rows are processed by window functions using ORDER BY within OVER. (The window ORDER BY does not even have to match the order in which the rows are output.) Here is an example:

SELECT depname, empno, salary,
       row_number() OVER (PARTITION BY depname ORDER BY salary DESC)
FROM empsalary;
  depname  | empno | salary | row_number
-----------+-------+--------+------------
 develop   |     8 |   6000 |          1
 develop   |    10 |   5200 |          2
 develop   |    11 |   5200 |          3
 develop   |     9 |   4500 |          4
 develop   |     7 |   4200 |          5
 personnel |     2 |   3900 |          1
 personnel |     5 |   3500 |          2
 sales     |     1 |   5000 |          1
 sales     |     4 |   4800 |          2
 sales     |     3 |   4800 |          3
(10 rows)

As shown here, the row_number window function assigns sequential numbers to the rows within each partition, in the order defined by the ORDER BY clause (with tied rows numbered in an unspecified order). row_number needs no explicit parameter, because its behavior is entirely determined by the OVER clause.

The rows considered by a window function are those of the “virtual table” produced by the query's FROM clause as filtered by its WHERE, GROUP BY, and HAVING clauses if any. For example, a row removed because it does not meet the WHERE condition is not seen by any window function. A query can contain multiple window functions that slice up the data in different ways using different OVER clauses, but they all act on the same collection of rows defined by this virtual table.

We already saw that ORDER BY can be omitted if the ordering of rows is not important. It is also possible to omit PARTITION BY, in which case there is a single partition containing all rows.

There is another important concept associated with window functions: for each row, there is a set of rows within its partition called its window frame. Some window functions act only on the rows of the window frame, rather than of the whole partition. By default, if ORDER BY is supplied then the frame consists of all rows from the start of the partition up through the current row, plus any following rows that are equal to the current row according to the ORDER BY clause. When ORDER BY is omitted the default frame consists of all rows in the partition. [5] Here is an example using sum:

SELECT salary, sum(salary) OVER () FROM empsalary;
 salary |  sum
--------+-------
   5200 | 47100
   5000 | 47100
   3500 | 47100
   4800 | 47100
   3900 | 47100
   4200 | 47100
   4500 | 47100
   4800 | 47100
   6000 | 47100
   5200 | 47100
(10 rows)

Above, since there is no ORDER BY in the OVER clause, the window frame is the same as the partition, which for lack of PARTITION BY is the whole table; in other words each sum is taken over the whole table and so we get the same result for each output row. But if we add an ORDER BY clause, we get very different results:

SELECT salary, sum(salary) OVER (ORDER BY salary) FROM empsalary;
 salary |  sum
--------+-------
   3500 |  3500
   3900 |  7400
   4200 | 11600
   4500 | 16100
   4800 | 25700
   4800 | 25700
   5000 | 30700
   5200 | 41100
   5200 | 41100
   6000 | 47100
(10 rows)

Here the sum is taken from the first (lowest) salary up through the current one, including any duplicates of the current one (notice the results for the duplicated salaries).

Window functions are permitted only in the SELECT list and the ORDER BY clause of the query. They are forbidden elsewhere, such as in GROUP BY, HAVING and WHERE clauses. This is because they logically execute after the processing of those clauses. Also, window functions execute after non-window aggregate functions. This means it is valid to include an aggregate function call in the arguments of a window function, but not vice versa.

If there is a need to filter or group rows after the window calculations are performed, you can use a sub-select. For example:

SELECT depname, empno, salary, enroll_date
FROM
  (SELECT depname, empno, salary, enroll_date,
     row_number() OVER (PARTITION BY depname ORDER BY salary DESC, empno) AS pos
     FROM empsalary
  ) AS ss
WHERE pos < 3;

The above query only shows the rows from the inner query having row_number less than 3 (that is, the first two rows for each department).

When a query involves multiple window functions, it is possible to write out each one with a separate OVER clause, but this is duplicative and error-prone if the same windowing behavior is wanted for several functions. Instead, each windowing behavior can be named in a WINDOW clause and then referenced in OVER. For example:

SELECT sum(salary) OVER w, avg(salary) OVER w
  FROM empsalary
  WINDOW w AS (PARTITION BY depname ORDER BY salary DESC);

More details about window functions can be found in Section 4.2.8, Section 9.22, Section 7.2.5, and the SELECT reference page.



[5] There are options to define the window frame in other ways, but this tutorial does not cover them. See Section 4.2.8 for details.

22.2. Eigendecompositions Open the notebook in SageMaker Studio Lab

Assigned source reading · Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola

Dive into Deep Learning — the authors and contributors; text CC BY-SA 4.0; accompanying code under its separately stated license.

Original source · Creative Commons Attribution-ShareAlike 4.0 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

22.2. Eigendecompositions
Open the notebook in SageMaker Studio Lab

Eigenvalues are often one of the most useful notions we will encounter when studying linear algebra, however, as a beginner, it is easy to overlook their importance. Below, we introduce eigendecomposition and try to convey some sense of just why it is so important.

Suppose that we have a matrix \(A\) with the following entries:

(22.2.1)\[\begin{split}\mathbf{A} = \begin{bmatrix} 2 & 0 \\ 0 & -1 \end{bmatrix}.\end{split}\]

If we apply \(A\) to any vector \(\mathbf{v} = [x, y]^\top\), we obtain a vector \(\mathbf{A}\mathbf{v} = [2x, -y]^\top\). This has an intuitive interpretation: stretch the vector to be twice as wide in the \(x\)-direction, and then flip it in the \(y\)-direction.

However, there are some vectors for which something remains unchanged. Namely \([1, 0]^\top\) gets sent to \([2, 0]^\top\) and \([0, 1]^\top\) gets sent to \([0, -1]^\top\). These vectors are still in the same line, and the only modification is that the matrix stretches them by a factor of \(2\) and \(-1\) respectively. We call such vectors eigenvectors and the factor they are stretched by eigenvalues.

In general, if we can find a number \(\lambda\) and a vector \(\mathbf{v}\) such that

(22.2.2)\[\mathbf{A}\mathbf{v} = \lambda \mathbf{v}.\]

We say that \(\mathbf{v}\) is an eigenvector for \(A\) and \(\lambda\) is an eigenvalue.

22.2.1. Finding Eigenvalues

Let’s figure out how to find them. By subtracting off the \(\lambda \mathbf{v}\) from both sides, and then factoring out the vector, we see the above is equivalent to:

(22.2.3)\[(\mathbf{A} - \lambda \mathbf{I})\mathbf{v} = 0.\]

For (22.2.3) to happen, we see that \((\mathbf{A} - \lambda \mathbf{I})\) must compress some direction down to zero, hence it is not invertible, and thus the determinant is zero. Thus, we can find the eigenvalues by finding for what \(\lambda\) is \(\det(\mathbf{A}-\lambda \mathbf{I}) = 0\). Once we find the eigenvalues, we can solve \(\mathbf{A}\mathbf{v} = \lambda \mathbf{v}\) to find the associated eigenvector(s).

22.2.1.1. An Example

Let’s see this with a more challenging matrix

(22.2.4)\[\begin{split}\mathbf{A} = \begin{bmatrix} 2 & 1\\ 2 & 3 \end{bmatrix}.\end{split}\]

If we consider \(\det(\mathbf{A}-\lambda \mathbf{I}) = 0\), we see this is equivalent to the polynomial equation \(0 = (2-\lambda)(3-\lambda)-2 = (4-\lambda)(1-\lambda)\). Thus, two eigenvalues are \(4\) and \(1\). To find the associated vectors, we then need to solve

(22.2.5)\[\begin{split}\begin{bmatrix} 2 & 1\\ 2 & 3 \end{bmatrix}\begin{bmatrix}x \\ y\end{bmatrix} = \begin{bmatrix}x \\ y\end{bmatrix} \; \textrm{and} \; \begin{bmatrix} 2 & 1\\ 2 & 3 \end{bmatrix}\begin{bmatrix}x \\ y\end{bmatrix} = \begin{bmatrix}4x \\ 4y\end{bmatrix} .\end{split}\]

We can solve this with the vectors \([1, -1]^\top\) and \([1, 2]^\top\) respectively.

We can check this in code using the built-in numpy.linalg.eig routine.

%matplotlib inline
import torch
from IPython import display
from d2l import torch as d2l

torch.linalg.eig(torch.tensor([[2, 1], [2, 3]], dtype=torch.float64))
torch.return_types.linalg_eig(
eigenvalues=tensor([1.+0.j, 4.+0.j], dtype=torch.complex128),
eigenvectors=tensor([[-0.7071+0.j, -0.4472+0.j],
        [ 0.7071+0.j, -0.8944+0.j]], dtype=torch.complex128))

Note that numpy normalizes the eigenvectors to be of length one, whereas we took ours to be of arbitrary length. Additionally, the choice of sign is arbitrary. However, the vectors computed are parallel to the ones we found by hand with the same eigenvalues.

22.2.2. Decomposing Matrices

Let’s continue the previous example one step further. Let

(22.2.6)\[\begin{split}\mathbf{W} = \begin{bmatrix} 1 & 1 \\ -1 & 2 \end{bmatrix},\end{split}\]

be the matrix where the columns are the eigenvectors of the matrix \(\mathbf{A}\). Let

(22.2.7)\[\begin{split}\boldsymbol{\Sigma} = \begin{bmatrix} 1 & 0 \\ 0 & 4 \end{bmatrix},\end{split}\]

be the matrix with the associated eigenvalues on the diagonal. Then the definition of eigenvalues and eigenvectors tells us that

(22.2.8)\[\mathbf{A}\mathbf{W} =\mathbf{W} \boldsymbol{\Sigma} .\]

The matrix \(W\) is invertible, so we may multiply both sides by \(W^{-1}\) on the right, we see that we may write

(22.2.9)\[\mathbf{A} = \mathbf{W} \boldsymbol{\Sigma} \mathbf{W}^{-1}.\]

In the next section we will see some nice consequences of this, but for now we need only know that such a decomposition will exist as long as we can find a full collection of linearly independent eigenvectors (so that \(W\) is invertible).

22.2.3. Operations on Eigendecompositions

One nice thing about eigendecompositions (22.2.9) is that we can write many operations we usually encounter cleanly in terms of the eigendecomposition. As a first example, consider:

(22.2.10)\[\mathbf{A}^n = \overbrace{\mathbf{A}\cdots \mathbf{A}}^{\textrm{$n$ times}} = \overbrace{(\mathbf{W}\boldsymbol{\Sigma} \mathbf{W}^{-1})\cdots(\mathbf{W}\boldsymbol{\Sigma} \mathbf{W}^{-1})}^{\textrm{$n$ times}} = \mathbf{W}\overbrace{\boldsymbol{\Sigma}\cdots\boldsymbol{\Sigma}}^{\textrm{$n$ times}}\mathbf{W}^{-1} = \mathbf{W}\boldsymbol{\Sigma}^n \mathbf{W}^{-1}.\]

This tells us that for any positive power of a matrix, the eigendecomposition is obtained by just raising the eigenvalues to the same power. The same can be shown for negative powers, so if we want to invert a matrix we need only consider

(22.2.11)\[\mathbf{A}^{-1} = \mathbf{W}\boldsymbol{\Sigma}^{-1} \mathbf{W}^{-1},\]

or in other words, just invert each eigenvalue. This will work as long as each eigenvalue is non-zero, so we see that invertible is the same as having no zero eigenvalues.

Indeed, additional work can show that if \(\lambda_1, \ldots, \lambda_n\) are the eigenvalues of a matrix, then the determinant of that matrix is

(22.2.12)\[\det(\mathbf{A}) = \lambda_1 \cdots \lambda_n,\]

or the product of all the eigenvalues. This makes sense intuitively because whatever stretching \(\mathbf{W}\) does, \(W^{-1}\) undoes it, so in the end the only stretching that happens is by multiplication by the diagonal matrix \(\boldsymbol{\Sigma}\), which stretches volumes by the product of the diagonal elements.

Finally, recall that the rank was the maximum number of linearly independent columns of your matrix. By examining the eigendecomposition closely, we can see that the rank is the same as the number of non-zero eigenvalues of \(\mathbf{A}\).

The examples could continue, but hopefully the point is clear: eigendecomposition can simplify many linear-algebraic computations and is a fundamental operation underlying many numerical algorithms and much of the analysis that we do in linear algebra.

22.2.4. Eigendecompositions of Symmetric Matrices

It is not always possible to find enough linearly independent eigenvectors for the above process to work. For instance the matrix

(22.2.13)\[\begin{split}\mathbf{A} = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix},\end{split}\]

has only a single eigenvector, namely \((1, 0)^\top\). To handle such matrices, we require more advanced techniques than we can cover (such as the Jordan Normal Form, or Singular Value Decomposition). We will often need to restrict our attention to those matrices where we can guarantee the existence of a full set of eigenvectors.

The most commonly encountered family are the symmetric matrices, which are those matrices where \(\mathbf{A} = \mathbf{A}^\top\). In this case, we may take \(W\) to be an orthogonal matrix—a matrix whose columns are all length one vectors that are at right angles to one another, where \(\mathbf{W}^\top = \mathbf{W}^{-1}\)—and all the eigenvalues will be real. Thus, in this special case, we can write (22.2.9) as

(22.2.14)\[\mathbf{A} = \mathbf{W}\boldsymbol{\Sigma}\mathbf{W}^\top .\]

22.2.5. Gershgorin Circle Theorem

Eigenvalues are often difficult to reason with intuitively. If presented an arbitrary matrix, there is little that can be said about what the eigenvalues are without computing them. There is, however, one theorem that can make it easy to approximate well if the largest values are on the diagonal.

Let \(\mathbf{A} = (a_{ij})\) be any square matrix (\(n\times n\)). We will define \(r_i = \sum_{j \neq i} |a_{ij}|\). Let \(\mathcal{D}_i\) represent the disc in the complex plane with center \(a_{ii}\) radius \(r_i\). Then, every eigenvalue of \(\mathbf{A}\) is contained in one of the \(\mathcal{D}_i\).

This can be a bit to unpack, so let’s look at an example. Consider the matrix:

(22.2.15)\[\begin{split}\mathbf{A} = \begin{bmatrix} 1.0 & 0.1 & 0.1 & 0.1 \\ 0.1 & 3.0 & 0.2 & 0.3 \\ 0.1 & 0.2 & 5.0 & 0.5 \\ 0.1 & 0.3 & 0.5 & 9.0 \end{bmatrix}.\end{split}\]

We have \(r_1 = 0.3\), \(r_2 = 0.6\), \(r_3 = 0.8\) and \(r_4 = 0.9\). The matrix is symmetric, so all eigenvalues are real. This means that all of our eigenvalues will be in one of the ranges of

(22.2.16)\[[a_{11}-r_1, a_{11}+r_1] = [0.7, 1.3],\]
(22.2.17)\[[a_{22}-r_2, a_{22}+r_2] = [2.4, 3.6],\]
(22.2.18)\[[a_{33}-r_3, a_{33}+r_3] = [4.2, 5.8],\]
(22.2.19)\[[a_{44}-r_4, a_{44}+r_4] = [8.1, 9.9].\]

Performing the numerical computation shows that the eigenvalues are approximately \(0.99\), \(2.97\), \(4.95\), \(9.08\), all comfortably inside the ranges provided.

A = torch.tensor([[1.0, 0.1, 0.1, 0.1],
              [0.1, 3.0, 0.2, 0.3],
              [0.1, 0.2, 5.0, 0.5],
              [0.1, 0.3, 0.5, 9.0]])

v, _ = torch.linalg.eig(A)
v
tensor([0.9923+0.j, 9.0803+0.j, 4.9539+0.j, 2.9734+0.j])

In this way, eigenvalues can be approximated, and the approximations will be fairly accurate in the case that the diagonal is significantly larger than all the other elements.

It is a small thing, but with a complex and subtle topic like eigendecomposition, it is good to get any intuitive grasp we can.

22.2.6. A Useful Application: The Growth of Iterated Maps

Now that we understand what eigenvectors are in principle, let’s see how they can be used to provide a deep understanding of a problem central to neural network behavior: proper weight initialization.

22.2.6.1. Eigenvectors as Long Term Behavior

The full mathematical investigation of the initialization of deep neural networks is beyond the scope of the text, but we can see a toy version here to understand how eigenvalues can help us see how these models work. As we know, neural networks operate by interspersing layers of linear transformations with non-linear operations. For simplicity here, we will assume that there is no non-linearity, and that the transformation is a single repeated matrix operation \(A\), so that the output of our model is

(22.2.20)\[\mathbf{v}_{out} = \mathbf{A}\cdot \mathbf{A}\cdots \mathbf{A} \mathbf{v}_{in} = \mathbf{A}^N \mathbf{v}_{in}.\]

When these models are initialized, \(A\) is taken to be a random matrix with Gaussian entries, so let’s make one of those. To be concrete, we start with a mean zero, variance one Gaussian distributed \(5 \times 5\) matrix.

torch.manual_seed(42)

k = 5
A = torch.randn(k, k, dtype=torch.float64)
A
tensor([[ 0.2996,  0.2424,  0.2832, -0.2329,  0.6712],
        [ 0.7818, -1.7903, -1.7484,  0.1735, -0.1182],
        [-1.7446, -0.4695,  0.4573,  0.5177, -0.2771],
        [-0.6641,  0.6551,  0.2616, -1.5265, -0.3311],
        [-0.6378,  0.1072,  0.7096,  0.3009, -0.2869]], dtype=torch.float64)

22.2.6.2. Behavior on Random Data

For simplicity in our toy model, we will assume that the data vector we feed in \(\mathbf{v}_{in}\) is a random five dimensional Gaussian vector. Let’s think about what we want to have happen. For context, lets think of a generic ML problem, where we are trying to turn input data, like an image, into a prediction, like the probability the image is a picture of a cat. If repeated application of \(\mathbf{A}\) stretches a random vector out to be very long, then small changes in input will be amplified into large changes in output—tiny modifications of the input image would lead to vastly different predictions. This does not seem right!

On the flip side, if \(\mathbf{A}\) shrinks random vectors to be shorter, then after running through many layers, the vector will essentially shrink to nothing, and the output will not depend on the input. This is also clearly not right either!

We need to walk the narrow line between growth and decay to make sure that our output changes depending on our input, but not much!

Let’s see what happens when we repeatedly multiply our matrix \(\mathbf{A}\) against a random input vector, and keep track of the norm.

# Calculate the sequence of norms after repeatedly applying `A`
v_in = torch.randn(k, 1, dtype=torch.float64)

norm_list = [torch.norm(v_in).item()]
for i in range(1, 100):
    v_in = A @ v_in
    norm_list.append(torch.norm(v_in).item())

d2l.plot(torch.arange(0, 100), norm_list, 'Iteration', 'Value')
../_images/output_eigendecomposition_ee2e00_39_0.svg

The norm is growing uncontrollably! Indeed if we take the list of quotients, we will see a pattern.

# Compute the scaling factor of the norms
norm_ratio_list = []
for i in range(1, 100):
    norm_ratio_list.append(norm_list[i]/norm_list[i - 1])

d2l.plot(torch.arange(1, 100), norm_ratio_list, 'Iteration', 'Ratio')
../_images/output_eigendecomposition_ee2e00_51_0.svg

If we look at the last portion of the above computation, we see that the random vector is stretched by a factor of 1.974459321485[...], where the portion at the end shifts a little, but the stretching factor is stable.

22.2.6.3. Relating Back to Eigenvectors

We have seen that eigenvectors and eigenvalues correspond to the amount something is stretched, but that was for specific vectors, and specific stretches. Let’s take a look at what they are for \(\mathbf{A}\). A bit of a caveat here: it turns out that to see them all, we will need to go to complex numbers. You can think of these as stretches and rotations. By taking the norm of the complex number (square root of the sums of squares of real and imaginary parts) we can measure that stretching factor. Let’s also sort them.

# Compute the eigenvalues
eigs = torch.linalg.eig(A).eigenvalues.tolist()
norm_eigs = [torch.abs(torch.tensor(x)) for x in eigs]
norm_eigs.sort()
print(f'norms of eigenvalues: {norm_eigs}')
norms of eigenvalues: [tensor(0.3490), tensor(1.1296), tensor(1.1296), tensor(1.1828), tensor(2.4532)]

22.2.6.4. An Observation

We see something a bit unexpected happening here: that number we identified before for the long term stretching of our matrix \(\mathbf{A}\) applied to a random vector is exactly (accurate to thirteen decimal places!) the largest eigenvalue of \(\mathbf{A}\). This is clearly not a coincidence!

But, if we now think about what is happening geometrically, this starts to make sense. Consider a random vector. This random vector points a little in every direction, so in particular, it points at least a little bit in the same direction as the eigenvector of \(\mathbf{A}\) associated with the largest eigenvalue. This is so important that it is called the principle eigenvalue and principle eigenvector. After applying \(\mathbf{A}\), our random vector gets stretched in every possible direction, as is associated with every possible eigenvector, but it is stretched most of all in the direction associated with this principle eigenvector. What this means is that after apply in \(A\), our random vector is longer, and points in a direction closer to being aligned with the principle eigenvector. After applying the matrix many times, the alignment with the principle eigenvector becomes closer and closer until, for all practical purposes, our random vector has been transformed into the principle eigenvector! Indeed this algorithm is the basis for what is known as the power iteration for finding the largest eigenvalue and eigenvector of a matrix. For details see, for example, (Golub and Van Loan, 1996).

22.2.6.5. Fixing the Normalization

Now, from above discussions, we concluded that we do not want a random vector to be stretched or squished at all, we would like random vectors to stay about the same size throughout the entire process. To do so, we now rescale our matrix by this principle eigenvalue so that the largest eigenvalue is instead now just one. Let’s see what happens in this case.

# Rescale the matrix `A`
A /= norm_eigs[-1]

# Do the same experiment again
v_in = torch.randn(k, 1, dtype=torch.float64)

norm_list = [torch.norm(v_in).item()]
for i in range(1, 100):
    v_in = A @ v_in
    norm_list.append(torch.norm(v_in).item())

d2l.plot(torch.arange(0, 100), norm_list, 'Iteration', 'Value')
../_images/output_eigendecomposition_ee2e00_75_0.svg

We can also plot the ratio between consecutive norms as before and see that indeed it stabilizes.

# Also plot the ratio
norm_ratio_list = []
for i in range(1, 100):
    norm_ratio_list.append(norm_list[i]/norm_list[i-1])

d2l.plot(torch.arange(1, 100), norm_ratio_list, 'Iteration', 'Ratio')
../_images/output_eigendecomposition_ee2e00_87_0.svg

22.2.7. Discussion

We now see exactly what we hoped for! After normalizing the matrices by the principal eigenvalue, we see that the random data does not explode as before, but rather eventually equilibrates to a specific value. It would be nice to be able to do these things from first principles, and it turns out that if we look deeply at the mathematics of it, we can see that the largest eigenvalue of a large random matrix with independent mean zero, variance one Gaussian entries is on average about \(\sqrt{n}\), or in our case \(\sqrt{5} \approx 2.2\), due to a fascinating fact known as the circular law (Ginibre, 1965). The relationship between the eigenvalues (and a related object called singular values) of random matrices has been shown to have deep connections to proper initialization of neural networks as was discussed in Pennington et al. (2017) and subsequent works.

22.2.8. Summary

  • Eigenvectors are vectors which are stretched by a matrix without changing direction.

  • Eigenvalues are the amount that the eigenvectors are stretched by the application of the matrix.

  • The eigendecomposition of a matrix can allow for many operations to be reduced to operations on the eigenvalues.

  • The Gershgorin Circle Theorem can provide approximate values for the eigenvalues of a matrix.

  • The behavior of iterated matrix powers depends primarily on the size of the largest eigenvalue. This understanding has many applications in the theory of neural network initialization.

22.2.9. Exercises

  1. What are the eigenvalues and eigenvectors of

    (22.2.21)\[\begin{split}\mathbf{A} = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix}?\end{split}\]
  2. What are the eigenvalues and eigenvectors of the following matrix, and what is strange about this example compared to the previous one?

    (22.2.22)\[\begin{split}\mathbf{A} = \begin{bmatrix} 2 & 1 \\ 0 & 2 \end{bmatrix}.\end{split}\]
  3. Without computing the eigenvalues, is it possible that the smallest eigenvalue of the following matrix is less that \(0.5\)? Note: this problem can be done in your head.

    (22.2.23)\[\begin{split}\mathbf{A} = \begin{bmatrix} 3.0 & 0.1 & 0.3 & 1.0 \\ 0.1 & 1.0 & 0.1 & 0.2 \\ 0.3 & 0.1 & 5.0 & 0.0 \\ 1.0 & 0.2 & 0.0 & 1.8 \end{bmatrix}.\end{split}\]

3.7. Weight Decay Open the notebook in SageMaker Studio Lab

Assigned source reading · Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola

Dive into Deep Learning — the authors and contributors; text CC BY-SA 4.0; accompanying code under its separately stated license.

Original source · Creative Commons Attribution-ShareAlike 4.0 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

3.7. Weight Decay
Open the notebook in SageMaker Studio Lab

Now that we have characterized the problem of overfitting, we can introduce our first regularization technique. Recall that we can always mitigate overfitting by collecting more training data. However, that can be costly, time consuming, or entirely out of our control, making it impossible in the short run. For now, we can assume that we already have as much high-quality data as our resources permit and focus the tools at our disposal when the dataset is taken as a given.

Recall that in our polynomial regression example (Section 3.6.2.1) we could limit our model’s capacity by tweaking the degree of the fitted polynomial. Indeed, limiting the number of features is a popular technique for mitigating overfitting. However, simply tossing aside features can be too blunt an instrument. Sticking with the polynomial regression example, consider what might happen with high-dimensional input. The natural extensions of polynomials to multivariate data are called monomials, which are simply products of powers of variables. The degree of a monomial is the sum of the powers. For example, \(x_1^2 x_2\), and \(x_3 x_5^2\) are both monomials of degree 3.

Note that the number of terms with degree \(d\) blows up rapidly as \(d\) grows larger. Given \(k\) variables, the number of monomials of degree \(d\) is \({k - 1 + d} \choose {k - 1}\). Even small changes in degree, say from \(2\) to \(3\), dramatically increase the complexity of our model. Thus we often need a more fine-grained tool for adjusting function complexity.

%matplotlib inline
import torch
from torch import nn
from d2l import torch as d2l

3.7.1. Norms and Weight Decay

Rather than directly manipulating the number of parameters, weight decay, operates by restricting the values that the parameters can take. More commonly called \(\ell_2\) regularization outside of deep learning circles when optimized by minibatch stochastic gradient descent, weight decay might be the most widely used technique for regularizing parametric machine learning models. The technique is motivated by the basic intuition that among all functions \(f\), the function \(f = 0\) (assigning the value \(0\) to all inputs) is in some sense the simplest, and that we can measure the complexity of a function by the distance of its parameters from zero. But how precisely should we measure the distance between a function and zero? There is no single right answer. In fact, entire branches of mathematics, including parts of functional analysis and the theory of Banach spaces, are devoted to addressing such issues.

One simple interpretation might be to measure the complexity of a linear function \(f(\mathbf{x}) = \mathbf{w}^\top \mathbf{x}\) by some norm of its weight vector, e.g., \(\| \mathbf{w} \|^2\). Recall that we introduced the \(\ell_2\) norm and \(\ell_1\) norm, which are special cases of the more general \(\ell_p\) norm, in Section 2.3.11. The most common method for ensuring a small weight vector is to add its norm as a penalty term to the problem of minimizing the loss. Thus we replace our original objective, minimizing the prediction loss on the training labels, with new objective, minimizing the sum of the prediction loss and the penalty term. Now, if our weight vector grows too large, our learning algorithm might focus on minimizing the weight norm \(\| \mathbf{w} \|^2\) rather than minimizing the training error. That is exactly what we want. To illustrate things in code, we revive our previous example from Section 3.1 for linear regression. There, our loss was given by

(3.7.1)\[L(\mathbf{w}, b) = \frac{1}{n}\sum_{i=1}^n \frac{1}{2}\left(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\right)^2.\]

Recall that \(\mathbf{x}^{(i)}\) are the features, \(y^{(i)}\) is the label for any data example \(i\), and \((\mathbf{w}, b)\) are the weight and bias parameters, respectively. To penalize the size of the weight vector, we must somehow add \(\| \mathbf{w} \|^2\) to the loss function, but how should the model trade off the standard loss for this new additive penalty? In practice, we characterize this trade-off via the regularization constant \(\lambda\), a nonnegative hyperparameter that we fit using validation data:

(3.7.2)\[L(\mathbf{w}, b) + \frac{\lambda}{2} \|\mathbf{w}\|^2.\]

For \(\lambda = 0\), we recover our original loss function. For \(\lambda > 0\), we restrict the size of \(\| \mathbf{w} \|\). We divide by \(2\) by convention: when we take the derivative of a quadratic function, the \(2\) and \(1/2\) cancel out, ensuring that the expression for the update looks nice and simple. The astute reader might wonder why we work with the squared norm and not the standard norm (i.e., the Euclidean distance). We do this for computational convenience. By squaring the \(\ell_2\) norm, we remove the square root, leaving the sum of squares of each component of the weight vector. This makes the derivative of the penalty easy to compute: the sum of derivatives equals the derivative of the sum.

Moreover, you might ask why we work with the \(\ell_2\) norm in the first place and not, say, the \(\ell_1\) norm. In fact, other choices are valid and popular throughout statistics. While \(\ell_2\)-regularized linear models constitute the classic ridge regression algorithm, \(\ell_1\)-regularized linear regression is a similarly fundamental method in statistics, popularly known as lasso regression. One reason to work with the \(\ell_2\) norm is that it places an outsize penalty on large components of the weight vector. This biases our learning algorithm towards models that distribute weight evenly across a larger number of features. In practice, this might make them more robust to measurement error in a single variable. By contrast, \(\ell_1\) penalties lead to models that concentrate weights on a small set of features by clearing the other weights to zero. This gives us an effective method for feature selection, which may be desirable for other reasons. For example, if our model only relies on a few features, then we may not need to collect, store, or transmit data for the other (dropped) features.

Using the same notation in (3.1.11), minibatch stochastic gradient descent updates for \(\ell_2\)-regularized regression as follows:

(3.7.3)\[\begin{aligned} \mathbf{w} & \leftarrow \left(1- \eta\lambda \right) \mathbf{w} - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}} \mathbf{x}^{(i)} \left(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\right). \end{aligned}\]

As before, we update \(\mathbf{w}\) based on the amount by which our estimate differs from the observation. However, we also shrink the size of \(\mathbf{w}\) towards zero. That is why the method is sometimes called “weight decay”: given the penalty term alone, our optimization algorithm decays the weight at each step of training. In contrast to feature selection, weight decay offers us a mechanism for continuously adjusting the complexity of a function. Smaller values of \(\lambda\) correspond to less constrained \(\mathbf{w}\), whereas larger values of \(\lambda\) constrain \(\mathbf{w}\) more considerably. Whether we include a corresponding bias penalty \(b^2\) can vary across implementations, and may vary across layers of a neural network. Often, we do not regularize the bias term. Besides, although \(\ell_2\) regularization may not be equivalent to weight decay for other optimization algorithms, the idea of regularization through shrinking the size of weights still holds true.

3.7.2. High-Dimensional Linear Regression

We can illustrate the benefits of weight decay through a simple synthetic example.

First, we generate some data as before:

(3.7.4)\[y = 0.05 + \sum_{i = 1}^d 0.01 x_i + \epsilon \textrm{ where } \epsilon \sim \mathcal{N}(0, 0.01^2).\]

In this synthetic dataset, our label is given by an underlying linear function of our inputs, corrupted by Gaussian noise with zero mean and standard deviation 0.01. For illustrative purposes, we can make the effects of overfitting pronounced, by increasing the dimensionality of our problem to \(d = 200\) and working with a small training set with only 20 examples.

class Data(d2l.DataModule):
    def __init__(self, num_train, num_val, num_inputs, batch_size):
        self.save_hyperparameters()
        n = num_train + num_val
        self.X = torch.randn(n, num_inputs)
        noise = torch.randn(n, 1) * 0.01
        w, b = torch.ones((num_inputs, 1)) * 0.01, 0.05
        self.y = torch.matmul(self.X, w) + b + noise

    def get_dataloader(self, train):
        i = slice(0, self.num_train) if train else slice(self.num_train, None)
        return self.get_tensorloader([self.X, self.y], train, i)

3.7.3. Implementation from Scratch

Now, let’s try implementing weight decay from scratch. Since minibatch stochastic gradient descent is our optimizer, we just need to add the squared \(\ell_2\) penalty to the original loss function.

3.7.3.1. Defining \(\ell_2\) Norm Penalty

Perhaps the most convenient way of implementing this penalty is to square all terms in place and sum them.

def l2_penalty(w):
    return (w ** 2).sum() / 2

3.7.3.2. Defining the Model

In the final model, the linear regression and the squared loss have not changed since Section 3.4, so we will just define a subclass of d2l.LinearRegressionScratch. The only change here is that our loss now includes the penalty term.

class WeightDecayScratch(d2l.LinearRegressionScratch):
    def __init__(self, num_inputs, lambd, lr, sigma=0.01):
        super().__init__(num_inputs, lr, sigma)
        self.save_hyperparameters()

    def loss(self, y_hat, y):
        return (super().loss(y_hat, y) +
                self.lambd * l2_penalty(self.w))

The following code fits our model on the training set with 20 examples and evaluates it on the validation set with 100 examples.

data = Data(num_train=20, num_val=100, num_inputs=200, batch_size=5)
trainer = d2l.Trainer(max_epochs=10)

def train_scratch(lambd):
    model = WeightDecayScratch(num_inputs=200, lambd=lambd, lr=0.01)
    model.board.yscale='log'
    trainer.fit(model, data)
    print('L2 norm of w:', float(l2_penalty(model.w)))

3.7.3.3. Training without Regularization

We now run this code with lambd = 0, disabling weight decay. Note that we overfit badly, decreasing the training error but not the validation error—a textbook case of overfitting.

train_scratch(0)
L2 norm of w: 0.009948714636266232
../_images/output_weight-decay_63fc98_78_1.svg

3.7.3.4. Using Weight Decay

Below, we run with substantial weight decay. Note that the training error increases but the validation error decreases. This is precisely the effect we expect from regularization.

train_scratch(3)
L2 norm of w: 0.0017270983662456274
../_images/output_weight-decay_63fc98_93_1.svg

3.7.4. Concise Implementation

Because weight decay is ubiquitous in neural network optimization, the deep learning framework makes it especially convenient, integrating weight decay into the optimization algorithm itself for easy use in combination with any loss function. Moreover, this integration serves a computational benefit, allowing implementation tricks to add weight decay to the algorithm, without any additional computational overhead. Since the weight decay portion of the update depends only on the current value of each parameter, the optimizer must touch each parameter once anyway.

Below, we specify the weight decay hyperparameter directly through weight_decay when instantiating our optimizer. By default, PyTorch decays both weights and biases simultaneously, but we can configure the optimizer to handle different parameters according to different policies. Here, we only set weight_decay for the weights (the net.weight parameters), hence the bias (the net.bias parameter) will not decay.

class WeightDecay(d2l.LinearRegression):
    def __init__(self, wd, lr):
        super().__init__(lr)
        self.save_hyperparameters()
        self.wd = wd

    def configure_optimizers(self):
        return torch.optim.SGD([
            {'params': self.net.weight, 'weight_decay': self.wd},
            {'params': self.net.bias}], lr=self.lr)

The plot looks similar to that when we implemented weight decay from scratch. However, this version runs faster and is easier to implement, benefits that will become more pronounced as you address larger problems and this work becomes more routine.

model = WeightDecay(wd=3, lr=0.01)
model.board.yscale='log'
trainer.fit(model, data)

print('L2 norm of w:', float(l2_penalty(model.get_w_b()[0])))
L2 norm of w: 0.013779522851109505
../_images/output_weight-decay_63fc98_126_1.svg

So far, we have touched upon one notion of what constitutes a simple linear function. However, even for simple nonlinear functions, the situation can be much more complex. To see this, the concept of reproducing kernel Hilbert space (RKHS) allows one to apply tools introduced for linear functions in a nonlinear context. Unfortunately, RKHS-based algorithms tend to scale poorly to large, high-dimensional data. In this book we will often adopt the common heuristic whereby weight decay is applied to all layers of a deep network.

3.7.5. Summary

Regularization is a common method for dealing with overfitting. Classical regularization techniques add a penalty term to the loss function (when training) to reduce the complexity of the learned model. One particular choice for keeping the model simple is using an \(\ell_2\) penalty. This leads to weight decay in the update steps of the minibatch stochastic gradient descent algorithm. In practice, the weight decay functionality is provided in optimizers from deep learning frameworks. Different sets of parameters can have different update behaviors within the same training loop.

3.7.6. Exercises

  1. Experiment with the value of \(\lambda\) in the estimation problem in this section. Plot training and validation accuracy as a function of \(\lambda\). What do you observe?

  2. Use a validation set to find the optimal value of \(\lambda\). Is it really the optimal value? Does this matter?

  3. What would the update equations look like if instead of \(\|\mathbf{w}\|^2\) we used \(\sum_i |w_i|\) as our penalty of choice (\(\ell_1\) regularization)?

  4. We know that \(\|\mathbf{w}\|^2 = \mathbf{w}^\top \mathbf{w}\). Can you find a similar equation for matrices (see the Frobenius norm in Section 2.3.11)?

  5. Review the relationship between training error and generalization error. In addition to weight decay, increased training, and the use of a model of suitable complexity, what other ways might help us deal with overfitting?

  6. In Bayesian statistics we use the product of prior and likelihood to arrive at a posterior via \(P(w \mid x) \propto P(x \mid w) P(w)\). How can you identify \(P(w)\) with regularization?

9.2. Converting Raw Text into Sequence Data Open the notebook in SageMaker Studio Lab

Assigned source reading · Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola

Dive into Deep Learning — the authors and contributors; text CC BY-SA 4.0; accompanying code under its separately stated license.

Original source · Creative Commons Attribution-ShareAlike 4.0 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

9.2. Converting Raw Text into Sequence Data
Open the notebook in SageMaker Studio Lab

Throughout this book, we will often work with text data represented as sequences of words, characters, or word pieces. To get going, we will need some basic tools for converting raw text into sequences of the appropriate form. Typical preprocessing pipelines execute the following steps:

  1. Load text as strings into memory.

  2. Split the strings into tokens (e.g., words or characters).

  3. Build a vocabulary dictionary to associate each vocabulary element with a numerical index.

  4. Convert the text into sequences of numerical indices.

import collections
import random
import re
import torch
from d2l import torch as d2l

9.2.1. Reading the Dataset

Here, we will work with H. G. Wells’ The Time Machine, a book containing just over 30,000 words. While real applications will typically involve significantly larger datasets, this is sufficient to demonstrate the preprocessing pipeline. The following _download method reads the raw text into a string.

class TimeMachine(d2l.DataModule): #@save
    """The Time Machine dataset."""
    def _download(self):
        fname = d2l.download(d2l.DATA_URL + 'timemachine.txt', self.root,
                             '090b5e7e70c295757f55df93cb0a180b9691891a')
        with open(fname) as f:
            return f.read()

data = TimeMachine()
raw_text = data._download()
raw_text[:60]
'The Time Machine, by H. G. Wells [1898]nnnnnInnnThe Time Tra'

For simplicity, we ignore punctuation and capitalization when preprocessing the raw text.

@d2l.add_to_class(TimeMachine)  #@save
def _preprocess(self, text):
    return re.sub('[^A-Za-z]+', ' ', text).lower()

text = data._preprocess(raw_text)
text[:60]
'the time machine by h g wells i the time traveller for so it'

9.2.2. Tokenization

Tokens are the atomic (indivisible) units of text. Each time step corresponds to 1 token, but what precisely constitutes a token is a design choice. For example, we could represent the sentence “Baby needs a new pair of shoes” as a sequence of 7 words, where the set of all words comprise a large vocabulary (typically tens or hundreds of thousands of words). Or we would represent the same sentence as a much longer sequence of 30 characters, using a much smaller vocabulary (there are only 256 distinct ASCII characters). Below, we tokenize our preprocessed text into a sequence of characters.

@d2l.add_to_class(TimeMachine)  #@save
def _tokenize(self, text):
    return list(text)

tokens = data._tokenize(text)
','.join(tokens[:30])
't,h,e, ,t,i,m,e, ,m,a,c,h,i,n,e, ,b,y, ,h, ,g, ,w,e,l,l,s, '

9.2.3. Vocabulary

These tokens are still strings. However, the inputs to our models must ultimately consist of numerical inputs. Next, we introduce a class for constructing vocabularies, i.e., objects that associate each distinct token value with a unique index. First, we determine the set of unique tokens in our training corpus. We then assign a numerical index to each unique token. Rare vocabulary elements are often dropped for convenience. Whenever we encounter a token at training or test time that had not been previously seen or was dropped from the vocabulary, we represent it by a special “<unk>” token, signifying that this is an unknown value.

class Vocab:  #@save
    """Vocabulary for text."""
    def __init__(self, tokens=[], min_freq=0, reserved_tokens=[]):
        # Flatten a 2D list if needed
        if tokens and isinstance(tokens[0], list):
            tokens = [token for line in tokens for token in line]
        # Count token frequencies
        counter = collections.Counter(tokens)
        self.token_freqs = sorted(counter.items(), key=lambda x: x[1],
                                  reverse=True)
        # The list of unique tokens
        self.idx_to_token = list(sorted(set(['<unk>'] + reserved_tokens + [
            token for token, freq in self.token_freqs if freq >= min_freq])))
        self.token_to_idx = {token: idx
                             for idx, token in enumerate(self.idx_to_token)}

    def __len__(self):
        return len(self.idx_to_token)

    def __getitem__(self, tokens):
        if not isinstance(tokens, (list, tuple)):
            return self.token_to_idx.get(tokens, self.unk)
        return [self.__getitem__(token) for token in tokens]

    def to_tokens(self, indices):
        if hasattr(indices, '__len__') and len(indices) > 1:
            return [self.idx_to_token[int(index)] for index in indices]
        return self.idx_to_token[indices]

    @property
    def unk(self):  # Index for the unknown token
        return self.token_to_idx['<unk>']

We now construct a vocabulary for our dataset, converting the sequence of strings into a list of numerical indices. Note that we have not lost any information and can easily convert our dataset back to its original (string) representation.

vocab = Vocab(tokens)
indices = vocab[tokens[:10]]
print('indices:', indices)
print('words:', vocab.to_tokens(indices))
indices: [21, 9, 6, 0, 21, 10, 14, 6, 0, 14]
words: ['t', 'h', 'e', ' ', 't', 'i', 'm', 'e', ' ', 'm']

9.2.4. Putting It All Together

Using the above classes and methods, we package everything into the following build method of the TimeMachine class, which returns corpus, a list of token indices, and vocab, the vocabulary of The Time Machine corpus. The modifications we did here are: (i) we tokenize text into characters, not words, to simplify the training in later sections; (ii) corpus is a single list, not a list of token lists, since each text line in The Time Machine dataset is not necessarily a sentence or paragraph.

@d2l.add_to_class(TimeMachine)  #@save
def build(self, raw_text, vocab=None):
    tokens = self._tokenize(self._preprocess(raw_text))
    if vocab is None: vocab = Vocab(tokens)
    corpus = [vocab[token] for token in tokens]
    return corpus, vocab

corpus, vocab = data.build(raw_text)
len(corpus), len(vocab)
(173428, 28)

9.2.5. Exploratory Language Statistics

Using the real corpus and the Vocab class defined over words, we can inspect basic statistics concerning word use in our corpus. Below, we construct a vocabulary from words used in The Time Machine and print the ten most frequently occurring of them.

words = text.split()
vocab = Vocab(words)
vocab.token_freqs[:10]
[('the', 2261),
 ('i', 1267),
 ('and', 1245),
 ('of', 1155),
 ('a', 816),
 ('to', 695),
 ('was', 552),
 ('in', 541),
 ('that', 443),
 ('my', 440)]

Note that the ten most frequent words are not all that descriptive. You might even imagine that we might see a very similar list if we had chosen any book at random. Articles like “the” and “a”, pronouns like “i” and “my”, and prepositions like “of”, “to”, and “in” occur often because they serve common syntactic roles. Such words that are common but not particularly descriptive are often called stop words and, in previous generations of text classifiers based on so-called bag-of-words representations, they were most often filtered out. However, they carry meaning and it is not necessary to filter them out when working with modern RNN- and Transformer-based neural models. If you look further down the list, you will notice that word frequency decays quickly. The \(10^{\textrm{th}}\) most frequent word is less than \(1/5\) as common as the most popular. Word frequency tends to follow a power law distribution (specifically the Zipfian) as we go down the ranks. To get a better idea, we plot the figure of the word frequency.

freqs = [freq for token, freq in vocab.token_freqs]
d2l.plot(freqs, xlabel='token: x', ylabel='frequency: n(x)',
         xscale='log', yscale='log')
../_images/output_text-sequence_e0a8c3_110_0.svg

After dealing with the first few words as exceptions, all the remaining words roughly follow a straight line on a log–log plot. This phenomenon is captured by Zipf’s law, which states that the frequency \(n_i\) of the \(i^\textrm{th}\) most frequent word is:

(9.2.1)\[n_i \propto \frac{1}{i^\alpha},\]

which is equivalent to

(9.2.2)\[\log n_i = -\alpha \log i + c,\]

where \(\alpha\) is the exponent that characterizes the distribution and \(c\) is a constant. This should already give us pause for thought if we want to model words by counting statistics. After all, we will significantly overestimate the frequency of the tail, also known as the infrequent words. But what about the other word combinations, such as two consecutive words (bigrams), three consecutive words (trigrams), and beyond? Let’s see whether the bigram frequency behaves in the same manner as the single word (unigram) frequency.

bigram_tokens = ['--'.join(pair) for pair in zip(words[:-1], words[1:])]
bigram_vocab = Vocab(bigram_tokens)
bigram_vocab.token_freqs[:10]
[('of--the', 309),
 ('in--the', 169),
 ('i--had', 130),
 ('i--was', 112),
 ('and--the', 109),
 ('the--time', 102),
 ('it--was', 99),
 ('to--the', 85),
 ('as--i', 78),
 ('of--a', 73)]

One thing is notable here. Out of the ten most frequent word pairs, nine are composed of both stop words and only one is relevant to the actual book—“the time”. Furthermore, let’s see whether the trigram frequency behaves in the same manner.

trigram_tokens = ['--'.join(triple) for triple in zip(
    words[:-2], words[1:-1], words[2:])]
trigram_vocab = Vocab(trigram_tokens)
trigram_vocab.token_freqs[:10]
[('the--time--traveller', 59),
 ('the--time--machine', 30),
 ('the--medical--man', 24),
 ('it--seemed--to', 16),
 ('it--was--a', 15),
 ('here--and--there', 15),
 ('seemed--to--me', 14),
 ('i--did--not', 14),
 ('i--saw--the', 13),
 ('i--began--to', 13)]

Now, let’s visualize the token frequency among these three models: unigrams, bigrams, and trigrams.

bigram_freqs = [freq for token, freq in bigram_vocab.token_freqs]
trigram_freqs = [freq for token, freq in trigram_vocab.token_freqs]
d2l.plot([freqs, bigram_freqs, trigram_freqs], xlabel='token: x',
         ylabel='frequency: n(x)', xscale='log', yscale='log',
         legend=['unigram', 'bigram', 'trigram'])
../_images/output_text-sequence_e0a8c3_155_0.svg

This figure is quite exciting. First, beyond unigram words, sequences of words also appear to be following Zipf’s law, albeit with a smaller exponent \(\alpha\) in (9.2.1), depending on the sequence length. Second, the number of distinct \(n\)-grams is not that large. This gives us hope that there is quite a lot of structure in language. Third, many \(n\)-grams occur very rarely. This makes certain methods unsuitable for language modeling and motivates the use of deep learning models. We will discuss this in the next section.

9.2.6. Summary

Text is among the most common forms of sequence data encountered in deep learning. Common choices for what constitutes a token are characters, words, and word pieces. To preprocess text, we usually (i) split text into tokens; (ii) build a vocabulary to map token strings to numerical indices; and (iii) convert text data into token indices for models to manipulate. In practice, the frequency of words tends to follow Zipf’s law. This is true not just for individual words (unigrams), but also for \(n\)-grams.

9.2.7. Exercises

  1. In the experiment of this section, tokenize text into words and vary the min_freq argument value of the Vocab instance. Qualitatively characterize how changes in min_freq impact the size of the resulting vocabulary.

  2. Estimate the exponent of Zipfian distribution for unigrams, bigrams, and trigrams in this corpus.

  3. Find some other sources of data (download a standard machine learning dataset, pick another public domain book, scrape a website, etc). For each, tokenize the data at both the word and character levels. How do the vocabulary sizes compare with The Time Machine corpus at equivalent values of min_freq. Estimate the exponent of the Zipfian distribution corresponding to the unigram and bigram distributions for these corpora. How do they compare with the values that you observed for The Time Machine corpus?

queue — A synchronized queue class

Assigned source reading · Python Software Foundation and Python documentation contributors

Copyright © 2001 Python Software Foundation; All Rights Reserved

Original source · Python Software Foundation License Version 2 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Full license and notices
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
¶
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
   the Individual or Organization ("Licensee") accessing and otherwise using this
   software ("Python") in source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., "Copyright © 2001 Python Software Foundation; All Rights
   Reserved" are retained in Python alone or in any derivative version
   prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python or any part thereof, and wants to make the
   derivative work available to others as provided herein, then Licensee hereby
   agrees to include in any such work a brief summary of the changes made to Python.

4. PSF is making Python available to Licensee on an "AS IS" basis.
   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship
   of agency, partnership, or joint venture between PSF and Licensee.  This License
   Agreement does not grant permission to use PSF trademarks or trade name in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.

8. By copying, installing or otherwise using Python, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.

queue — A synchronized queue class

Source code: Lib/queue.py


The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.

The module implements three types of queue, which differ only in the order in which the entries are retrieved. In a FIFO queue, the first tasks added are the first retrieved. In a LIFO queue, the most recently added entry is the first retrieved (operating like a stack). With a priority queue, the entries are kept sorted (using the heapq module) and the lowest valued entry is retrieved first.

Internally, those three types of queues use locks to temporarily block competing threads; however, they are not designed to handle reentrancy within a thread.

In addition, the module implements a “simple” FIFO queue type, SimpleQueue, whose specific implementation provides additional guarantees in exchange for the smaller functionality.

The queue module defines the following classes and exceptions:

class queue.Queue(maxsize=0)

Constructor for a FIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.

class queue.LifoQueue(maxsize=0)

Constructor for a LIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.

class queue.PriorityQueue(maxsize=0)

Constructor for a priority queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.

The lowest valued entries are retrieved first (the lowest valued entry is the one that would be returned by min(entries)). A typical pattern for entries is a tuple in the form: (priority_number, data).

If the data elements are not comparable, the data can be wrapped in a class that ignores the data item and only compares the priority number:

from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class PrioritizedItem:
    priority: int
    item: Any=field(compare=False)
class queue.SimpleQueue

Constructor for an unbounded FIFO queue. Simple queues lack advanced functionality such as task tracking.

Simple queues are generic over the type of their items.

Added in version 3.7.

exception queue.Empty

Exception raised when non-blocking get() (or get_nowait()) is called on a Queue object which is empty.

exception queue.Full

Exception raised when non-blocking put() (or put_nowait()) is called on a Queue object which is full.

exception queue.ShutDown

Exception raised when put() or get() is called on a Queue object which has been shut down.

Added in version 3.13.

Queue Objects

Queue objects (Queue, LifoQueue, or PriorityQueue) provide the public methods described below.

Queue.qsize()

Return the approximate size of the queue. Note, qsize() > 0 doesn’t guarantee that a subsequent get() will not block, nor will qsize() < maxsize guarantee that put() will not block.

Queue.empty()

Return True if the queue is empty, False otherwise. If empty() returns True it doesn’t guarantee that a subsequent call to put() will not block. Similarly, if empty() returns False it doesn’t guarantee that a subsequent call to get() will not block.

Queue.full()

Return True if the queue is full, False otherwise. If full() returns True it doesn’t guarantee that a subsequent call to get() will not block. Similarly, if full() returns False it doesn’t guarantee that a subsequent call to put() will not block.

Queue.put(item, block=True, timeout=None)

Put item into the queue. If optional args block is true and timeout is None (the default), block if necessary until a free slot is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Full exception if no free slot was available within that time. Otherwise (block is false), put an item on the queue if a free slot is immediately available, else raise the Full exception (timeout is ignored in that case).

Raises ShutDown if the queue has been shut down.

Queue.put_nowait(item)

Equivalent to put(item, block=False).

Queue.get(block=True, timeout=None)

Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

Prior to 3.0 on POSIX systems, and for all versions on Windows, if block is true and timeout is None, this operation goes into an uninterruptible wait on an underlying lock. This means that no exceptions can occur, and in particular a SIGINT will not trigger a KeyboardInterrupt.

Raises ShutDown if the queue has been shut down and is empty, or if the queue has been shut down immediately.

Queue.get_nowait()

Equivalent to get(False).

Two methods are offered to support tracking whether enqueued tasks have been fully processed by daemon consumer threads.

Queue.task_done()

Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete.

If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue).

Raises a ValueError if called more times than there were items placed in the queue.

Queue.join()

Blocks until all items in the queue have been gotten and processed.

The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.

Waiting for task completion

Example of how to wait for enqueued tasks to be completed:

import threading
import queue

q = queue.Queue()

def worker():
    while True:
        item = q.get()
        print(f'Working on {item}')
        print(f'Finished {item}')
        q.task_done()

# Turn-on the worker thread.
threading.Thread(target=worker, daemon=True).start()

# Send thirty task requests to the worker.
for item in range(30):
    q.put(item)

# Block until all tasks are done.
q.join()
print('All work completed')

Terminating queues

When no longer needed, Queue objects can be wound down until empty or terminated immediately with a hard shutdown.

Queue.shutdown(immediate=False)

Put a Queue instance into a shutdown mode.

The queue can no longer grow. Future calls to put() raise ShutDown. Currently blocked callers of put() will be unblocked and will raise ShutDown in the formerly blocked thread.

If immediate is false (the default), the queue can be wound down normally with get() calls to extract tasks that have already been loaded.

And if task_done() is called for each remaining task, a pending join() will be unblocked normally.

Once the queue is empty, future calls to get() will raise ShutDown.

If immediate is true, the queue is terminated immediately. The queue is drained to be completely empty and the count of unfinished tasks is reduced by the number of tasks drained. If unfinished tasks is zero, callers of join() are unblocked. Also, blocked callers of get() are unblocked and will raise ShutDown because the queue is empty.

Use caution when using join() with immediate set to true. This unblocks the join even when no work has been done on the tasks, violating the usual invariant for joining a queue.

Added in version 3.13.

SimpleQueue Objects

SimpleQueue objects provide the public methods described below.

SimpleQueue.qsize()

Return the approximate size of the queue. Note, qsize() > 0 doesn’t guarantee that a subsequent get() will not block.

SimpleQueue.empty()

Return True if the queue is empty, False otherwise. If empty() returns False it doesn’t guarantee that a subsequent call to get() will not block.

SimpleQueue.put(item, block=True, timeout=None)

Put item into the queue. The method never blocks and always succeeds (except for potential low-level errors such as failure to allocate memory). The optional args block and timeout are ignored and only provided for compatibility with Queue.put().

CPython implementation detail: This method has a C implementation which is reentrant. That is, a put() or get() call can be interrupted by another put() call in the same thread without deadlocking or corrupting internal state inside the queue. This makes it appropriate for use in destructors such as __del__ methods or weakref callbacks.

SimpleQueue.put_nowait(item)

Equivalent to put(item, block=False), provided for compatibility with Queue.put_nowait().

SimpleQueue.get(block=True, timeout=None)

Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

SimpleQueue.get_nowait()

Equivalent to get(False).

See also

Class multiprocessing.Queue

A queue class for use in a multi-processing (rather than multi-threading) context.

collections.deque is an alternative implementation of unbounded queues with fast atomic append() and popleft() operations that do not require locking and also support indexing.

venv — Creation of virtual environments

Assigned source reading · Python Software Foundation and Python documentation contributors

Copyright © 2001 Python Software Foundation; All Rights Reserved

Original source · Python Software Foundation License Version 2 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Full license and notices
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
¶
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
   the Individual or Organization ("Licensee") accessing and otherwise using this
   software ("Python") in source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., "Copyright © 2001 Python Software Foundation; All Rights
   Reserved" are retained in Python alone or in any derivative version
   prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python or any part thereof, and wants to make the
   derivative work available to others as provided herein, then Licensee hereby
   agrees to include in any such work a brief summary of the changes made to Python.

4. PSF is making Python available to Licensee on an "AS IS" basis.
   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship
   of agency, partnership, or joint venture between PSF and Licensee.  This License
   Agreement does not grant permission to use PSF trademarks or trade name in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.

8. By copying, installing or otherwise using Python, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.

venv — Creation of virtual environments

Added in version 3.3.

Source code: Lib/venv/


The venv module supports creating lightweight “virtual environments”, each with their own independent set of Python packages installed in their site directories. A virtual environment is created on top of an existing Python installation, known as the virtual environment’s “base” Python, and by default is isolated from the packages in the base environment, so that only those explicitly installed in the virtual environment are available. See Virtual Environments and site’s virtual environments documentation for more information.

When used from within a virtual environment, common installation tools such as pip will install Python packages into a virtual environment without needing to be told to do so explicitly.

A virtual environment is (amongst other things):

  • Used to contain a specific Python interpreter and software libraries and binaries which are needed to support a project (library or application). These are by default isolated from software in other virtual environments and Python interpreters and libraries installed in the operating system.

  • Contained in a directory, conventionally named .venv or venv in the project directory, or under a container directory for lots of virtual environments, such as ~/.virtualenvs.

  • Not checked into source control systems such as Git.

  • Considered as disposable – it should be simple to delete and recreate it from scratch. You don’t place any project code in the environment.

  • Not considered as movable or copyable – you just recreate the same environment in the target location.

See PEP 405 for more background on Python virtual environments.

Availability: not Android, not iOS, not WASI.

This module is not supported on mobile platforms or WebAssembly platforms.

Creating virtual environments

Virtual environments are created by executing the venv module:

python -m venv /path/to/new/virtual/environment

This creates the target directory (including parent directories as needed) and places a pyvenv.cfg file in it with a home key pointing to the Python installation from which the command was run. It also creates a bin (or Scripts on Windows) subdirectory containing a copy or symlink of the Python executable (as appropriate for the platform or arguments used at environment creation time). It also creates a lib/pythonX.Y/site-packages subdirectory (on Windows, this is Lib\site-packages). If an existing directory is specified, it will be re-used.

Changed in version 3.5: The use of venv is now recommended for creating virtual environments.

Deprecated since version 3.6, removed in version 3.8: pyvenv was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and replaced in 3.5 by executing venv directly.

On Windows, invoke the venv command as follows:

PS> python -m venv C:\path\to\new\virtual\environment

The command, if run with -h, will show the available options:

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            [--without-scm-ignore-files]
            ENV_DIR [ENV_DIR ...]

Creates virtual Python environments in one or more target directories.

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
ENV_DIR

A required argument specifying the directory to create the environment in.

--system-site-packages

Give the virtual environment access to the system site-packages directory.

Try to use symlinks rather than copies, when symlinks are not the default for the platform.

--copies

Try to use copies rather than symlinks, even when symlinks are the default for the platform.

--clear

Delete the contents of the environment directory if it already exists, before environment creation.

--upgrade

Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place.

--without-pip

Skips installing or upgrading pip in the virtual environment (pip is bootstrapped by default).

--prompt <PROMPT>

Provides an alternative prompt prefix for this environment.

--upgrade-deps

Upgrade core dependencies (pip) to the latest version in PyPI.

--without-scm-ignore-files

Skips adding SCM ignore files to the environment directory (Git is supported by default).

Changed in version 3.4: Installs pip by default, added the --without-pip and --copies options.

Changed in version 3.4: In earlier versions, if the target directory already existed, an error was raised, unless the --clear or --upgrade option was provided.

Changed in version 3.9: Add --upgrade-deps option to upgrade pip + setuptools to the latest on PyPI.

Changed in version 3.12: setuptools is no longer a core venv dependency.

Changed in version 3.13: Added the --without-scm-ignore-files option.

Changed in version 3.13: venv now creates a .gitignore file for Git by default.

Note

While symlinks are supported on Windows, they are not recommended. Of particular note is that double-clicking python.exe in File Explorer will resolve the symlink eagerly and ignore the virtual environment.

Note

On Microsoft Windows, it may be required to enable the Activate.ps1 script by setting the execution policy for the user. You can do this by issuing the following PowerShell command:

PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

See About Execution Policies for more information.

The created pyvenv.cfg file also includes the include-system-site-packages key, set to true if venv is run with the --system-site-packages option, false otherwise.

Unless the --without-pip option is given, ensurepip will be invoked to bootstrap pip into the virtual environment.

Multiple paths can be given to venv, in which case an identical virtual environment will be created, according to the given options, at each provided path.

How venvs work

When a Python interpreter is running from a virtual environment, sys.prefix and sys.exec_prefix point to the directories of the virtual environment, whereas sys.base_prefix and sys.base_exec_prefix point to those of the base Python used to create the environment. It is sufficient to check sys.prefix != sys.base_prefix to determine if the current interpreter is running from a virtual environment.

A virtual environment may be “activated” using a script in its binary directory (bin on POSIX; Scripts on Windows). This will prepend that directory to your PATH, so that running python will invoke the environment’s Python interpreter and you can run installed scripts without having to use their full path. The invocation of the activation script is platform-specific (<venv> must be replaced by the path to the directory containing the virtual environment):

Platform

Shell

Command to activate virtual environment

POSIX

bash/zsh

$ source <venv>/bin/activate

fish

$ source <venv>/bin/activate.fish

csh/tcsh

$ source <venv>/bin/activate.csh

pwsh

$ <venv>/bin/Activate.ps1

Windows

cmd.exe

C:\> <venv>\Scripts\activate.bat

PowerShell

PS C:\> <venv>\Scripts\Activate.ps1

Added in version 3.4: fish and csh activation scripts.

Added in version 3.8: PowerShell activation scripts installed under POSIX for PowerShell Core support.

You don’t specifically need to activate a virtual environment, as you can just specify the full path to that environment’s Python interpreter when invoking Python. Furthermore, all scripts installed in the environment should be runnable without activating it.

In order to achieve this, scripts installed into virtual environments have a “shebang” line which points to the environment’s Python interpreter, #!/<path-to-venv>/bin/python. This means that the script will run with that interpreter regardless of the value of PATH. On Windows, “shebang” line processing is supported if you have the Python install manager installed. Thus, double-clicking an installed script in a Windows Explorer window should run it with the correct interpreter without the environment needing to be activated or on the PATH.

When a virtual environment has been activated, the VIRTUAL_ENV environment variable is set to the path of the environment. Since explicitly activating a virtual environment is not required to use it, VIRTUAL_ENV cannot be relied upon to determine whether a virtual environment is being used.

Warning

Because scripts installed in environments should not expect the environment to be activated, their shebang lines contain the absolute paths to their environment’s interpreters. Because of this, environments are inherently non-portable, in the general case. You should always have a simple means of recreating an environment (for example, if you have a requirements file requirements.txt, you can invoke pip install -r requirements.txt using the environment’s pip to install all of the packages needed by the environment). If for any reason you need to move the environment to a new location, you should recreate it at the desired location and delete the one at the old location. If you move an environment because you moved a parent directory of it, you should recreate the environment in its new location. Otherwise, software installed into the environment may not work as expected.

You can deactivate a virtual environment by typing deactivate in your shell. The exact mechanism is platform-specific and is an internal implementation detail (typically, a script or shell function will be used).

API

The high-level method described above makes use of a simple API which provides mechanisms for third-party virtual environment creators to customize environment creation according to their needs, the EnvBuilder class.

class venv.EnvBuilder(system_site_packages=False, clear=False, symlinks=False, upgrade=False, with_pip=False, prompt=None, upgrade_deps=False, *, scm_ignore_files=frozenset())

The EnvBuilder class accepts the following keyword arguments on instantiation:

  • system_site_packages – a boolean value indicating that the system Python site-packages should be available to the environment (defaults to False).

  • clear – a boolean value which, if true, will delete the contents of any existing target directory, before creating the environment.

  • symlinks – a boolean value indicating whether to attempt to symlink the Python binary rather than copying.

  • upgrade – a boolean value which, if true, will upgrade an existing environment with the running Python - for use when that Python has been upgraded in-place (defaults to False).

  • with_pip – a boolean value which, if true, ensures pip is installed in the virtual environment. This uses ensurepip with the --default-pip option.

  • prompt – a string to be used after virtual environment is activated (defaults to None which means directory name of the environment would be used). If the special string "." is provided, the basename of the current directory is used as the prompt.

  • upgrade_deps – Update the base venv modules to the latest on PyPI

  • scm_ignore_files – Create ignore files based for the specified source control managers (SCM) in the iterable. Support is defined by having a method named create_{scm}_ignore_file. The only value supported by default is "git" via create_git_ignore_file().

Changed in version 3.4: Added the with_pip parameter

Changed in version 3.6: Added the prompt parameter

Changed in version 3.9: Added the upgrade_deps parameter

Changed in version 3.13: Added the scm_ignore_files parameter

EnvBuilder may be used as a base class.

create(env_dir)

Create a virtual environment by specifying the target directory (absolute or relative to the current directory) which is to contain the virtual environment. The create method will either create the environment in the specified directory, or raise an appropriate exception.

The create method of the EnvBuilder class illustrates the hooks available for subclass customization:

def create(self, env_dir):
    """
    Create a virtualized Python environment in a directory.
    env_dir is the target directory to create an environment in.
    """
    env_dir = os.path.abspath(env_dir)
    context = self.ensure_directories(env_dir)
    self.create_configuration(context)
    self.setup_python(context)
    self.setup_scripts(context)
    self.post_setup(context)

Each of the methods ensure_directories(), create_configuration(), setup_python(), setup_scripts() and post_setup() can be overridden.

ensure_directories(env_dir)

Creates the environment directory and all necessary subdirectories that don’t already exist, and returns a context object. This context object is just a holder for attributes (such as paths) for use by the other methods. If the EnvBuilder is created with the arg clear=True, contents of the environment directory will be cleared and then all necessary subdirectories will be recreated.

The returned context object is a types.SimpleNamespace with the following attributes:

  • env_dir - The location of the virtual environment. Used for __VENV_DIR__ in activation scripts (see install_scripts()).

  • env_name - The name of the virtual environment. Used for __VENV_NAME__ in activation scripts (see install_scripts()).

  • prompt - The prompt to be used by the activation scripts. Used for __VENV_PROMPT__ in activation scripts (see install_scripts()).

  • executable - The underlying Python executable used by the virtual environment. This takes into account the case where a virtual environment is created from another virtual environment.

  • inc_path - The include path for the virtual environment.

  • lib_path - The purelib path for the virtual environment.

  • platlib_path - The platlib path for the virtual environment.

  • bin_path - The script path for the virtual environment.

  • bin_name - The name of the script path relative to the virtual environment location. Used for __VENV_BIN_NAME__ in activation scripts (see install_scripts()).

  • env_exe - The name of the Python interpreter in the virtual environment. Used for __VENV_PYTHON__ in activation scripts (see install_scripts()).

  • env_exec_cmd - The name of the Python interpreter, taking into account filesystem redirections. This can be used to run Python in the virtual environment.

Changed in version 3.11: The venv sysconfig installation scheme is used to construct the paths of the created directories.

Changed in version 3.12: The attribute lib_path was added to the context, and the context object was documented.

Changed in version 3.15: The attribute platlib_path was added to the context.

create_configuration(context)

Creates the pyvenv.cfg configuration file in the environment.

setup_python(context)

Creates a copy or symlink to the Python executable in the environment. On POSIX systems, if a specific executable python3.x was used, symlinks to python and python3 will be created pointing to that executable, unless files with those names already exist.

setup_scripts(context)

Installs activation scripts appropriate to the platform into the virtual environment.

upgrade_dependencies(context)

Upgrades the core venv dependency packages (currently pip) in the environment. This is done by shelling out to the pip executable in the environment.

Added in version 3.9.

Changed in version 3.12: setuptools is no longer a core venv dependency.

post_setup(context)

A placeholder method which can be overridden in third party implementations to pre-install packages in the virtual environment or perform other post-creation steps.

install_scripts(context, path)

This method can be called from setup_scripts() or post_setup() in subclasses to assist in installing custom scripts into the virtual environment.

path is the path to a directory that should contain subdirectories common, posix, nt; each containing scripts destined for the bin directory in the environment. The contents of common and the directory corresponding to os.name are copied after some text replacement of placeholders:

  • __VENV_DIR__ is replaced with the absolute path of the environment directory.

  • __VENV_NAME__ is replaced with the environment name (final path segment of environment directory).

  • __VENV_PROMPT__ is replaced with the prompt (the environment name surrounded by parentheses and with a following space)

  • __VENV_BIN_NAME__ is replaced with the name of the bin directory (either bin or Scripts).

  • __VENV_PYTHON__ is replaced with the absolute path of the environment’s executable.

The directories are allowed to exist (for when an existing environment is being upgraded).

create_git_ignore_file(context)

Creates a .gitignore file within the virtual environment that causes the entire directory to be ignored by the Git source control manager.

Added in version 3.13.

Changed in version 3.7.2: Windows now uses redirector scripts for python[w].exe instead of copying the actual binaries. In 3.7.2 only setup_python() does nothing unless running from a build in the source tree.

Changed in version 3.7.3: Windows copies the redirector scripts as part of setup_python() instead of setup_scripts(). This was not the case in 3.7.2. When using symlinks, the original executables will be linked.

There is also a module-level convenience function:

venv.create(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None, upgrade_deps=False, *, scm_ignore_files=frozenset())

Create an EnvBuilder with the given keyword arguments, and call its create() method with the env_dir argument.

Added in version 3.3.

Changed in version 3.4: Added the with_pip parameter

Changed in version 3.6: Added the prompt parameter

Changed in version 3.9: Added the upgrade_deps parameter

Changed in version 3.13: Added the scm_ignore_files parameter

An example of extending EnvBuilder

The following script shows how to extend EnvBuilder by implementing a subclass which installs setuptools and pip into a created virtual environment:

import os
import os.path
from subprocess import Popen, PIPE
import sys
from threading import Thread
from urllib.parse import urlsplit
from urllib.request import urlretrieve
import venv

class ExtendedEnvBuilder(venv.EnvBuilder):
    """
    This builder installs setuptools and pip so that you can pip or
    easy_install other packages into the created virtual environment.

    :param nodist: If true, setuptools and pip are not installed into the
                   created virtual environment.
    :param nopip: If true, pip is not installed into the created
                  virtual environment.
    :param progress: If setuptools or pip are installed, the progress of the
                     installation can be monitored by passing a progress
                     callable. If specified, it is called with two
                     arguments: a string indicating some progress, and a
                     context indicating where the string is coming from.
                     The context argument can have one of three values:
                     'main', indicating that it is called from virtualize()
                     itself, and 'stdout' and 'stderr', which are obtained
                     by reading lines from the output streams of a subprocess
                     which is used to install the app.

                     If a callable is not specified, default progress
                     information is output to sys.stderr.
    """

    def __init__(self, *args, **kwargs):
        self.nodist = kwargs.pop('nodist', False)
        self.nopip = kwargs.pop('nopip', False)
        self.progress = kwargs.pop('progress', None)
        self.verbose = kwargs.pop('verbose', False)
        super().__init__(*args, **kwargs)

    def post_setup(self, context):
        """
        Set up any packages which need to be pre-installed into the
        virtual environment being created.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        os.environ['VIRTUAL_ENV'] = context.env_dir
        if not self.nodist:
            self.install_setuptools(context)
        # Can't install pip without setuptools
        if not self.nopip and not self.nodist:
            self.install_pip(context)

    def reader(self, stream, context):
        """
        Read lines from a subprocess' output stream and either pass to a progress
        callable (if specified) or write progress information to sys.stderr.
        """
        progress = self.progress
        while True:
            s = stream.readline()
            if not s:
                break
            if progress is not None:
                progress(s, context)
            else:
                if not self.verbose:
                    sys.stderr.write('.')
                else:
                    sys.stderr.write(s.decode('utf-8'))
                sys.stderr.flush()
        stream.close()

    def install_script(self, context, name, url):
        _, _, path, _, _ = urlsplit(url)
        fn = os.path.split(path)[-1]
        binpath = context.bin_path
        distpath = os.path.join(binpath, fn)
        # Download script into the virtual environment's binaries folder
        urlretrieve(url, distpath)
        progress = self.progress
        if self.verbose:
            term = '\n'
        else:
            term = ''
        if progress is not None:
            progress('Installing %s ...%s' % (name, term), 'main')
        else:
            sys.stderr.write('Installing %s ...%s' % (name, term))
            sys.stderr.flush()
        # Install in the virtual environment
        args = [context.env_exe, fn]
        p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
        t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
        t1.start()
        t2 = Thread(target=self.reader, args=(p.stderr, 'stderr'))
        t2.start()
        p.wait()
        t1.join()
        t2.join()
        if progress is not None:
            progress('done.', 'main')
        else:
            sys.stderr.write('done.\n')
        # Clean up - no longer needed
        os.unlink(distpath)

    def install_setuptools(self, context):
        """
        Install setuptools in the virtual environment.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        url = "https://bootstrap.pypa.io/ez_setup.py"
        self.install_script(context, 'setuptools', url)
        # clear up the setuptools archive which gets downloaded
        pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz')
        files = filter(pred, os.listdir(context.bin_path))
        for f in files:
            f = os.path.join(context.bin_path, f)
            os.unlink(f)

    def install_pip(self, context):
        """
        Install pip in the virtual environment.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        url = 'https://bootstrap.pypa.io/get-pip.py'
        self.install_script(context, 'pip', url)


def main(args=None):
    import argparse

    parser = argparse.ArgumentParser(prog=__name__,
                                     description='Creates virtual Python '
                                                 'environments in one or '
                                                 'more target '
                                                 'directories.')
    parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
                        help='A directory in which to create the '
                             'virtual environment.')
    parser.add_argument('--no-setuptools', default=False,
                        action='store_true', dest='nodist',
                        help="Don't install setuptools or pip in the "
                             "virtual environment.")
    parser.add_argument('--no-pip', default=False,
                        action='store_true', dest='nopip',
                        help="Don't install pip in the virtual "
                             "environment.")
    parser.add_argument('--system-site-packages', default=False,
                        action='store_true', dest='system_site',
                        help='Give the virtual environment access to the '
                             'system site-packages dir.')
    if os.name == 'nt':
        use_symlinks = False
    else:
        use_symlinks = True
    parser.add_argument('--symlinks', default=use_symlinks,
                        action='store_true', dest='symlinks',
                        help='Try to use symlinks rather than copies, '
                             'when symlinks are not the default for '
                             'the platform.')
    parser.add_argument('--clear', default=False, action='store_true',
                        dest='clear', help='Delete the contents of the '
                                           'virtual environment '
                                           'directory if it already '
                                           'exists, before virtual '
                                           'environment creation.')
    parser.add_argument('--upgrade', default=False, action='store_true',
                        dest='upgrade', help='Upgrade the virtual '
                                             'environment directory to '
                                             'use this version of '
                                             'Python, assuming Python '
                                             'has been upgraded '
                                             'in-place.')
    parser.add_argument('--verbose', default=False, action='store_true',
                        dest='verbose', help='Display the output '
                                             'from the scripts which '
                                             'install setuptools and pip.')
    options = parser.parse_args(args)
    if options.upgrade and options.clear:
        raise ValueError('you cannot supply --upgrade and --clear together.')
    builder = ExtendedEnvBuilder(system_site_packages=options.system_site,
                                   clear=options.clear,
                                   symlinks=options.symlinks,
                                   upgrade=options.upgrade,
                                   nodist=options.nodist,
                                   nopip=options.nopip,
                                   verbose=options.verbose)
    for d in options.dirs:
        builder.create(d)

if __name__ == '__main__':
    rc = 1
    try:
        main()
        rc = 0
    except Exception as e:
        print('Error: %s' % e, file=sys.stderr)
    sys.exit(rc)

This script is also available for download online.

Django Tutorial Part 4: Django admin site

Assigned source reading · Mozilla Contributors

MDN Web Docs — Mozilla Contributors

Original source · Creative Commons Attribution-ShareAlike 2.5 or later · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Django Tutorial Part 4: Django admin site

Now that we've created models for the LocalLibrary website, we'll use the Django Admin site to add some "real" book data. First we'll show you how to register the models with the admin site, then we'll show you how to log in and create some data. At the end of the article we will show some of the ways you can further improve the presentation of the Admin site.

Prerequisites: First complete: Django Tutorial Part 3: Using models.
Objective: To understand the benefits and limitations of the Django admin site, and use it to create some records for our models.

Overview

The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data. The admin application can also be useful for managing data in production, depending on the type of website. The Django project recommends it only for internal data management (i.e., just for use by admins, or people internal to your organization), as the model-centric approach is not necessarily the best possible interface for all users, and exposes a lot of unnecessary detail about the models.

All the configuration required to include the admin application in your website was done automatically when you created the skeleton project (for information about actual dependencies needed, see the Django docs here). As a result, all you must do to add your models to the admin application is to register them. At the end of this article we'll provide a brief demonstration of how you might further configure the admin area to better display our model data.

After registering the models we'll show how to create a new "superuser", log into the site, and create some books, authors, book instances, and genres. These will be useful for testing the views and templates we'll start creating in the next tutorial.

Registering models

First, open admin.py in the catalog application (/django-locallibrary-tutorial/catalog/admin.py). It currently looks like this — note that it already imports django.contrib.admin:

python
from django.contrib import admin

# Register your models here.

Register the models by copying the following text into the bottom of the file. This code imports the models and then calls admin.site.register to register each of them.

python
from .models import Author, Genre, Book, BookInstance, Language

admin.site.register(Book)
admin.site.register(Author)
admin.site.register(Genre)
admin.site.register(BookInstance)
admin.site.register(Language)

Note: The lines above assume that you accepted the challenge to create a model to represent the natural language of a book (see the models tutorial article)!

This is the simplest way of registering a model, or models, with the site. The admin site is highly customizable, and we'll talk more about the other ways of registering your models further down.

Creating a superuser

In order to log into the admin site, we need a user account with Staff status enabled. In order to view and create records we also need this user to have permissions to manage all our objects. You can create a "superuser" account that has full access to the site and all needed permissions using manage.py.

Call the following command, in the same directory as manage.py, to create the superuser. You will be prompted to enter a username, email address, and strong password.

bash
python3 manage.py createsuperuser

Once this command completes a new superuser will have been added to the database. Now restart the development server so we can test the login:

bash
python3 manage.py runserver

Logging in and using the site

To log into the site, open the /admin URL (e.g., http://127.0.0.1:8000/admin) and enter your new superuser userid and password credentials (you'll be redirected to the login page, and then back to the /admin URL after you've entered your details).

This part of the site displays all our models, grouped by installed application. You can click on a model name to go to a screen that lists all its associated records, and you can further click on those records to edit them. You can also directly click the Add link next to each model to start creating a record of that type.

Admin Site - Home page

Click on the Add link to the right of Books to create a new book (this will display a dialog much like the one below). Note how the titles of each field, the type of widget used, and the help_text (if any) match the values you specified in the model.

Enter values for the fields. You can create new authors or genres by pressing the + button next to the respective fields (or select existing values from the lists if you've already created them). When you're done you can press SAVE, Save and add another, or Save and continue editing to save the record.

Admin Site - Book Add

Note: At this point we'd like you to spend some time adding a few books, authors, languages, and genres (e.g., Fantasy) to your application. Make sure that each author and genre includes a couple of different books (this will make your list and detail views more interesting when we implement them later on in the article series).

When you've finished adding books, click on the Home link in the top bookmark to be taken back to the main admin page. Then click on the Books link to display the current list of books (or on one of the other links to see other model lists). Now that you've added a few books, the list might look similar to the screenshot below. The title of each book is displayed; this is the value returned in the Book model's __str__() method that we specified in the last article.

Admin Site - List of book objects

From this list you can delete books by selecting the checkbox next to the book you don't want, selecting the delete… action from the Action drop-down list, and then pressing the Go button. You can also add new books by pressing the ADD BOOK button.

You can edit a book by selecting its name in the link. The edit page for a book, shown below, is almost identical to the "Add" page. The main differences are the page title (Change book) and the addition of Delete, HISTORY and VIEW ON SITE buttons (this last button appears because we defined the get_absolute_url() method in our model).

Note: Clicking the VIEW ON SITE button raises a NoReverseMatch exception because the get_absolute_url() method attempts to reverse() a named URL mapping ('book-detail') that has not yet been defined. We'll define a URL mapping and associated view in Django Tutorial Part 6: Generic list and detail views.

Admin Site - Book Edit

Now navigate back to the Home page (using the Home link in the breadcrumb trail) and then view the Author and Genre lists — you should already have quite a few created from when you added the new books, but feel free to add some more.

What you won't have is any Book Instances, because these are not created from Books (although you can create a Book from a BookInstance — this is the nature of the ForeignKey field). Navigate back to the Home page and press the associated Add button to display the Add book instance screen below. Note the large, globally unique Id, which can be used to separately identify a single copy of a book in the library.

Admin Site - BookInstance Add

Create a number of these records for each of your books. Set the status as Available for at least some records and On loan for others. If the status is not Available, then also set a future Due back date.

That's it! You've now learned how to set up and use the administration site. You've also created records for Book, BookInstance, Genre, Language and Author that we'll be able to use once we create our own views and templates.

Advanced configuration

Django does a pretty good job of creating a basic admin site using the information from the registered models:

  • Each model has a list of individual records, identified by the string created with the model's __str__() method, and linked to detail views/forms for editing. By default, this view has an action menu at the top that you can use to perform bulk delete operations on records.
  • The model detail record forms for editing and adding records contain all the fields in the model, laid out vertically in their declaration order.

You can further customize the interface to make it even easier to use. Some of the things you can do are:

  • List views:

    • Add additional fields/information displayed for each record.
    • Add filters to select which records are listed, based on date or some other selection value (e.g., Book loan status).
    • Add additional options to the actions menu in list views and choose where this menu is displayed on the form.
  • Detail views

    • Choose which fields to display (or exclude), along with their order, grouping, whether they are editable, the widget used, orientation etc.
    • Add related fields to a record to allow inline editing (e.g., add the ability to add and edit book records while you're creating their author record).

In this section we're going to look at a few changes that will improve the interface for our LocalLibrary, including adding more information to Book and Author model lists, and improving the layout of their edit views. We won't change the Language and Genre model presentation because they only have one field each, so there is no real benefit in doing so!

You can find a complete reference of all the admin site customization choices in The Django Admin site (Django Docs).

Register a ModelAdmin class

To change how a model is displayed in the admin interface you define a ModelAdmin class (which describes the layout) and register it with the model.

Let's start with the Author model. Open admin.py in the catalog application (/django-locallibrary-tutorial/catalog/admin.py). Comment out your original registration (prefix it with a #) for the Author model:

python
# admin.site.register(Author)

Now add a new AuthorAdmin and registration as shown below.

python
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
    pass

# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)

Now we'll add ModelAdmin classes for Book, and BookInstance. We again need to comment out the original registrations:

python
# admin.site.register(Book)
# admin.site.register(BookInstance)

Now to create and register the new models; for the purpose of this demonstration, we'll instead use the @register decorator to register the models (this does exactly the same thing as the admin.site.register() syntax):

python
# Register the Admin classes for Book using the decorator
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    pass

# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
    pass

Currently all of our admin classes are empty (see pass) so the admin behavior will be unchanged! We can now extend these to define our model-specific admin behavior.

Configure list views

The LocalLibrary currently lists all authors using the object name generated from the model __str__() method. This is fine when you only have a few authors, but once you have many you may end up having duplicates. To differentiate them, or just because you want to show more interesting information about each author, you can use list_display to add additional fields to the view.

Replace your AuthorAdmin class with the code below. The field names to be displayed in the list are declared in a tuple in the required order, as shown (these are the same names as specified in your original model).

python
class AuthorAdmin(admin.ModelAdmin):
    list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')

Now navigate to the author list in your website. The fields above should now be displayed, like so:

Admin Site - Improved Author List

For our Book model we'll additionally display the author and genre. The author is a ForeignKey field (one-to-many) relationship, and so will be represented by the __str__() value for the associated record. Replace the BookAdmin class with the version below.

python
class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'display_genre')

Unfortunately we can't directly specify the genre field in list_display because it is a ManyToManyField (Django prevents this because there would be a large database access "cost" in doing so). Instead we'll define a display_genre function to get the information as a string (this is the function we've called above; we'll define it below).

Note: Getting the genre may not be a good idea here, because of the "cost" of the database operation. We're showing you how because calling functions in your models can be very useful for other reasons — for example to add a Delete link next to every item in the list.

Add the following code into your Book model (models.py). This creates a string from the first three values of the genre field (if they exist) and creates a short_description that can be used in the admin site for this method.

python
def display_genre(self):
    """Create a string for the Genre. This is required to display genre in Admin."""
    return ', '.join(genre.name for genre in self.genre.all()[:3])

display_genre.short_description = 'Genre'

After saving the model and updated admin, open your website and go to the Books list page; you should see a book list like the one below:

Admin Site - Improved Book List

The Genre model (and the Language model, if you defined one) both have a single field, so there is no point creating an additional model for them to display additional fields.

Note: It is worth updating the BookInstance model list to show at least the status and the expected return date. We've added that as a challenge at the end of this article!

Add list filters

Once you've got a lot of items in a list, it can be useful to be able to filter which items are displayed. This is done by listing fields in the list_filter attribute. Replace your current BookInstanceAdmin class with the code fragment below.

python
class BookInstanceAdmin(admin.ModelAdmin):
    list_filter = ('status', 'due_back')

The list view will now include a filter box to the right. Note how you can choose dates and status to filter the values:

Admin Site - BookInstance List Filters

Organize detail view layout

By default, the detail views lay out all fields vertically, in their order of declaration in the model. You can change the order of declaration, which fields are displayed (or excluded), whether sections are used to organize the information, whether fields are displayed horizontally or vertically, and even what edit widgets are used in the admin forms.

Note: The LocalLibrary models are relatively simple so there isn't a huge need for us to change the layout; we'll make some changes anyway however, just to show you how.

Controlling which fields are displayed and laid out

Update your AuthorAdmin class to add the fields line, as shown below:

python
class AuthorAdmin(admin.ModelAdmin):
    list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')

    fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]

The fields attribute lists just those fields that are to be displayed on the form, in order. Fields are displayed vertically by default, but will display horizontally if you further group them in a tuple (as shown in the "date" fields above).

In your website go to the author detail view — it should now appear as shown below:

Admin Site - Improved Author Detail

Note: You can also use the exclude attribute to declare a list of attributes to be excluded from the form (all other attributes in the model will be displayed).

Sectioning the detail view

You can add "sections" to group related model information within the detail form, using the fieldsets attribute.

In the BookInstance model we have information related to what the book is (i.e., name, imprint, and id) and when it will be available (status, due_back). We can add these to our BookInstanceAdmin class as shown below, using the fieldsets property.

python
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
    list_filter = ('status', 'due_back')

    fieldsets = (
        (None, {
            'fields': ('book', 'imprint', 'id')
        }),
        ('Availability', {
            'fields': ('status', 'due_back')
        }),
    )

Each section has its own title (or None, if you don't want a title) and an associated tuple of fields in a dictionary — the format is complicated to describe, but fairly easy to understand if you look at the code fragment immediately above.

Now navigate to a book instance view in your website; the form should appear as shown below:

Admin Site - Improved BookInstance Detail with sections

Inline editing of associated records

Sometimes it can make sense to be able to add associated records at the same time. For example, it may make sense to have both the book information and information about the specific copies you've got on the same detail page.

You can do this by declaring inlines, of type TabularInline (horizontal layout) or StackedInline (vertical layout, just like the default model layout). You can add the BookInstance information inline to our Book detail by specifying inlines in your BookAdmin:

python
class BooksInstanceInline(admin.TabularInline):
    model = BookInstance

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'display_genre')

    inlines = [BooksInstanceInline]

Now navigate to a view for a Book in your website — at the bottom you should now see the book instances relating to this book (immediately below the book's genre fields):

Admin Site - Book with Inlines

In this case all we've done is declare our tabular inline class, which just adds all fields from the inlined model. You can specify all sorts of additional information for the layout, including the fields to display, their order, whether they are read only or not, etc. (see TabularInline for more information).

Note: There are some painful limits in this functionality! In the screenshot above we have three existing book instances, followed by three placeholders for new book instances (which look very similar!). It would be better to have NO spare book instances by default and just add them with the Add another Book instance link, or to be able to just list the BookInstances as non-readable links from here. The first option can be done by setting the extra attribute to 0 in BooksInstanceInline model, try it by yourself.

Challenge yourself

We've learned a lot in this section, so now it is time for you to try a few things.

  1. For the BookInstance list view, add code to display the book, status, due back date, and id (rather than the default __str__() text).
  2. Add an inline listing of Book items to the Author detail view using the same approach as we did for Book/BookInstance.

Summary

That's it! You've now learned how to set up the administration site in both its simplest and improved form, how to create a superuser, and how to navigate the admin site and view, delete, and update records. Along the way you've created a bunch of Books, BookInstances, Genres, and Authors that we'll be able to list and display once we create our own view and templates.

Further reading