Complete Assigned Readings

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

7. Input and output

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.

7. Input and output

There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities.

7.1. Fancier output formatting

So far we’ve encountered two ways of writing values: expression statements and the print() function. (A third way is using the write() method of file objects; the standard output file can be referenced as sys.stdout. See the Library Reference for more information on this.)

Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are several ways to format output.

  • To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.

    >>> year = 2016
    >>> event = 'Referendum'
    >>> f'Results of the {year} {event}'
    'Results of the 2016 Referendum'
    
  • The str.format() method of strings requires more manual effort. You’ll still use { and } to mark where a variable will be substituted and can provide detailed formatting directives, but you’ll also need to provide the information to be formatted. In the following code block there are two examples of how to format variables:

    >>> yes_votes = 42_572_654
    >>> total_votes = 85_705_149
    >>> percentage = yes_votes / total_votes
    >>> '{:-9} YES votes  {:2.2%}'.format(yes_votes, percentage)
    ' 42572654 YES votes  49.67%'
    

    Notice how the yes_votes are padded with spaces and a negative sign only for negative numbers. The example also prints percentage multiplied by 100, with 2 decimal places and followed by a percent sign (see Format specification mini-language for details).

  • Finally, you can do all the string handling yourself by using string slicing and concatenation operations to create any layout you can imagine. The string type has some methods that perform useful operations for padding strings to a given column width.

When you don’t need fancy output but just want a quick display of some variables for debugging purposes, you can convert any value to a string with the repr() or str() functions.

The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax). For objects which don’t have a particular representation for human consumption, str() will return the same value as repr(). Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function. Strings, in particular, have two distinct representations.

Some examples:

>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
>>> hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
>>> repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"

The string module contains support for a simple templating approach based upon regular expressions, via string.Template. This offers yet another way to substitute values into strings, using placeholders like $x and replacing them with values from a dictionary. This syntax is easy to use, although it offers much less control for formatting.

7.1.1. Formatted string literals

Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as {expression}.

An optional format specifier can follow the expression. This allows greater control over how the value is formatted. The following example rounds pi to three places after the decimal:

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.

Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making columns line up.

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print(f'{name:10} ==> {phone:10d}')
...
Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678

Other modifiers can be used to convert the value before it is formatted. '!a' applies ascii(), '!s' applies str(), and '!r' applies repr():

>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.

The = specifier can be used to expand an expression to the text of the expression, an equal sign, then the representation of the evaluated expression:

>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'

See self-documenting expressions for more information on the = specifier. For a reference on these format specifications, see the reference guide for the Format specification mini-language.

7.1.2. The string format() method

Basic usage of the str.format() method looks like this:

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"

The brackets and characters within them (called format fields) are replaced with the objects passed into the str.format() method. A number in the brackets can be used to refer to the position of the object passed into the str.format() method.

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

If keyword arguments are used in the str.format() method, their values are referred to by using the name of the argument.

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

Positional and keyword arguments can be arbitrarily combined:

>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
...                                                    other='Georg'))
The story of Bill, Manfred, and Georg.

If you have a really long format string that you don’t want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by simply passing the dict and using square brackets '[]' to access the keys.

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...       'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This could also be done by passing the table dictionary as keyword arguments with the ** notation.

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This is particularly useful in combination with the built-in function vars(), which returns a dictionary containing all local variables:

>>> table = {k: str(v) for k, v in vars().items()}
>>> message = " ".join([f'{k}: ' + '{' + k +'};' for k in table.keys()])
>>> print(message.format(**table))
__name__: __main__; __doc__: None; __package__: None; __loader__: ...

As an example, the following lines produce a tidily aligned set of columns giving integers and their squares and cubes:

>>> for x in range(1, 11):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

For a complete overview of string formatting with str.format(), see Format string syntax.

7.1.3. Manual string formatting

Here’s the same table of squares and cubes, formatted manually:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # Note use of 'end' on previous line
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

(Note that the one space between each column was added by the way print() works: it always adds spaces between its arguments.)

The str.rjust() method of string objects right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods str.ljust() and str.center(). These methods do not write anything, they just return a new string. If the input string is too long, they don’t truncate it, but return it unchanged; this will mess up your column lay-out but that’s usually better than the alternative, which would be lying about a value. (If you really want truncation you can always add a slice operation, as in x.ljust(n)[:n].)

There is another method, str.zfill(), which pads a numeric string on the left with zeros. It understands about plus and minus signs:

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

7.1.4. Old string formatting

The % operator (modulo) can also be used for string formatting. Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values. This operation is commonly known as string interpolation. For example:

>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.

More information can be found in the printf-style String Formatting section.

7.2. Reading and writing files

open() returns a file object, and is most commonly used with two positional arguments: open(filename, mode)

>>> f = open('workfile', 'w')

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

Normally, files are opened in text mode, that means, you read and write strings from and to the file, which are encoded in a specific encoding. If encoding is not specified, the default is UTF-8 (see open()). Appending a 'b' to the mode opens the file in binary mode. Binary mode data is read and written as bytes objects. You can not specify encoding when opening file in binary mode.

In text mode, the default when reading is to convert platform-specific line endings (\n on Unix, \r\n on Windows) to just \n. When writing in text mode, the default is to convert occurrences of \n back to platform-specific line endings. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks:

>>> with open('workfile') as f:
...     read_data = f.read()

>>> # We can check that the file has been automatically closed.
>>> f.closed
True

If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it.

Warning

Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully.

After a file object is closed, either by a with statement or by calling f.close(), attempts to use the file object will automatically fail.

>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.

7.2.1. Methods of file objects

The rest of the examples in this section will assume that a file object called f has already been created.

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size characters (in text mode) or size bytes (in binary mode) are read and returned. If the end of the file has been reached, f.read() will return an empty string ('').

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:

>>> for line in f:
...     print(line, end='')
...
This is the first line of the file.
Second line of the file

If you want to read all the lines of a file in a list you can also use list(f) or f.readlines().

f.write(string) writes the contents of string to the file, returning the number of characters written.

>>> f.write('This is a test\n')
15

Other types of objects need to be converted – either to a string (in text mode) or a bytes object (in binary mode) – before writing them:

>>> value = ('the answer', 42)
>>> s = str(value)  # convert the tuple to string
>>> f.write(s)
18

f.tell() returns an integer giving the file object’s current position in the file represented as number of bytes from the beginning of the file when in binary mode and an opaque number when in text mode.

To change the file object’s position, use f.seek(offset, whence). The position is computed from adding offset to a reference point; the reference point is selected by the whence argument. A whence value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. whence can be omitted and defaults to 0, using the beginning of the file as the reference point.

>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)      # Go to the 6th byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)  # Go to the 3rd byte before the end
13
>>> f.read(1)
b'd'

In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2)) and the only valid offset values are those returned from the f.tell(), or zero. Any other offset value produces undefined behaviour.

File objects have some additional methods, such as isatty() and truncate() which are less frequently used; consult the Library Reference for a complete guide to file objects.

7.2.2. Saving structured data with json

Strings can easily be written to and read from a file. Numbers take a bit more effort, since the read() method only returns strings, which will have to be passed to a function like int(), which takes a string like '123' and returns its numeric value 123. When you want to save more complex data types like nested lists and dictionaries, parsing and serializing by hand becomes complicated.

Rather than having users constantly writing and debugging code to save complicated data types to files, Python allows you to use the popular data interchange format called JSON (JavaScript Object Notation). The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing. Reconstructing the data from the string representation is called deserializing. Between serializing and deserializing, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine.

Note

The JSON format is commonly used by modern applications to allow for data exchange. Many programmers are already familiar with it, which makes it a good choice for interoperability.

If you have an object x, you can view its JSON string representation with a simple line of code:

>>> import json
>>> x = [1, 'simple', 'list']
>>> json.dumps(x)
'[1, "simple", "list"]'

Another variant of the dumps() function, called dump(), simply serializes the object to a text file. So if f is a text file object opened for writing, we can do this:

json.dump(x, f)

To decode the object again, if f is a binary file or text file object which has been opened for reading:

x = json.load(f)

Note

JSON files must be encoded in UTF-8, the default encoding for text files.

This simple serialization technique can handle lists and dictionaries, but serializing arbitrary class instances in JSON requires a bit of extra effort. The reference for the json module contains an explanation of this.

See also

pickle - the pickle module

Contrary to JSON, pickle is a protocol which allows the serialization of arbitrarily complex Python objects. As such, it is specific to Python and cannot be used to communicate with applications written in other languages. It is also insecure by default: deserializing pickle data coming from an untrusted source can execute arbitrary code, if the data was crafted by a skilled attacker.

1 . 7 List of Data Structures

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.

1.7 List of Data Structures

Tables 1.1 and 1.2 summarize the performance of data structures in this book that implement each of the interfaces, List, USet, and SSet, described in Section 1.2. Figure 1.6 shows the dependencies between various chapters in this book. A dashed arrow indicates only a weak dependency, in which only a small part of the chapter depends on a previous chapter or only the main results of the previous chapter.


Table 1.1: Summary of List and USet implementations.
% latex2html id marker 4421
\resizebox{.98\textwidth}{!}{
\begin{threeparttable...
...{Denotes an \emph{expected} running time.}
\end{tablenotes}\end{threeparttable}}



Table 1.2: Summary of SSet and priority Queue implementations.

\begin{threeparttable}
% latex2html id marker 2868\begin{tabular}{\vert l\vert...
...nsuremath{\mathit{w}}}}-bit integer data.}\end{tablenotes}\end{threeparttable}


Figure 1.6: The dependencies between chapters in this book.
\includegraphics[width=\textwidth ]{figs-python/dependencies}



opendatastructures.org

3 . 2 DLList: A Doubly-Linked List

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


3.2 DLList: A Doubly-Linked List

A DLList (doubly-linked list) is very similar to an SLList except that each node $ \ensuremath{\ensuremath{\mathit{u}}}$ in a DLList has references to both the node $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{next}}}$ that follows it and the node $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{prev}}}$ that precedes it.

When implementing an SLList, we saw that there were always several special cases to worry about. For example, removing the last element from an SLList or adding an element to an empty SLList requires care to ensure that $ \ensuremath{\ensuremath{\mathit{head}}}$ and $ \ensuremath{\ensuremath{\mathit{tail}}}$ are correctly updated. In a DLList, the number of these special cases increases considerably. Perhaps the cleanest way to take care of all these special cases in a DLList is to introduce a $ \ensuremath{\ensuremath{\mathit{dummy}}}$ node. This is a node that does not contain any data, but acts as a placeholder so that there are no special nodes; every node has both a $ \ensuremath{\ensuremath{\mathit{next}}}$ and a $ \ensuremath{\ensuremath{\mathit{prev}}}$, with $ \ensuremath{\ensuremath{\mathit{dummy}}}$ acting as the node that follows the last node in the list and that precedes the first node in the list. In this way, the nodes of the list are (doubly-)linked into a cycle, as illustrated in Figure 3.2.

Figure 3.2: A DLList containing a,b,c,d,e.
\includegraphics[width=\textwidth ]{figs-python/dllist2}


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{initialize}(...
...my}}.\ensuremath{next} \gets \ensuremath{dummy}}\\
\end{flushleft}\end{leftbar}

Finding the node with a particular index in a DLList is easy; we can either start at the head of the list ( $ \ensuremath{\ensuremath{\mathit{dummy}}.\ensuremath{\mathit{next}}}$) and work forward, or start at the tail of the list ( $ \ensuremath{\ensuremath{\mathit{dummy}}.\ensuremath{\mathit{prev}}}$) and work backward. This allows us to reach the $ \ensuremath{\ensuremath{\mathit{i}}}$th node in $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensur...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$ time:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{get\_node}(\...
...bf{return}} \ensuremath{\ensuremath{\mathit{p}}}\\
\end{flushleft}\end{leftbar}

The $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operations are now also easy. We first find the $ \ensuremath{\ensuremath{\mathit{i}}}$th node and then get or set its $ \ensuremath{\ensuremath{\mathit{x}}}$ value:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{get}(\ensure...
...bf{return}} \ensuremath{\ensuremath{\mathit{y}}}\\
\end{flushleft}\end{leftbar}

The running time of these operations is dominated by the time it takes to find the $ \ensuremath{\ensuremath{\mathit{i}}}$th node, and is therefore $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensur...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$.

3.2.1 Adding and Removing

If we have a reference to a node $ \ensuremath{\ensuremath{\mathit{w}}}$ in a DLList and we want to insert a node $ \ensuremath{\ensuremath{\mathit{u}}}$ before $ \ensuremath{\ensuremath{\mathit{w}}}$, then this is just a matter of setting $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{next}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$, $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{prev}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{prev}}}}$, and then adjusting $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{prev}}.\ensuremath{\mathit{next}}}$ and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{next}}.\ensuremath{\mathit{prev}}}$. (See Figure 3.3.) Thanks to the dummy node, there is no need to worry about $ \ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{prev}}}$ or $ \ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{next}}}$ not existing.


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add\_before}...
...bf{return}} \ensuremath{\ensuremath{\mathit{u}}}\\
\end{flushleft}\end{leftbar}

Figure 3.3: Adding the node $ \ensuremath{\ensuremath{\mathit{u}}}$ before the node $ \ensuremath{\ensuremath{\mathit{w}}}$ in a DLList.
\includegraphics[scale=0.90909]{figs-python/dllist-addbefore}

Now, the list operation $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ is trivial to implement. We find the $ \ensuremath{\ensuremath{\mathit{i}}}$th node in the DLList and insert a new node $ \ensuremath{\ensuremath{\mathit{u}}}$ that contains $ \ensuremath{\ensuremath{\mathit{x}}}$ just before it.


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
...\mathrm{get\_node}(\ensuremath{\mathit{i}}), x})\\
\end{flushleft}\end{leftbar}

The only non-constant part of the running time of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ is the time it takes to find the $ \ensuremath{\ensuremath{\mathit{i}}}$th node (using $ \ensuremath{\mathrm{get\_node}(\ensuremath{\mathit{i}})}$). Thus, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ runs in $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}, \ensuremath{\ensu...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$ time.

Removing a node $ \ensuremath{\ensuremath{\mathit{w}}}$ from a DLList is easy. We only need to adjust pointers at $ \ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{next}}}$ and $ \ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{prev}}}$ so that they skip over $ \ensuremath{\ensuremath{\mathit{w}}}$. Again, the use of the dummy node eliminates the need to consider any special cases:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}(\ens...
...math{\ensuremath{\mathit{n}} - 1}\hspace*{1em} }\\
\end{flushleft}\end{leftbar}

Now the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operation is trivial. We find the node with index $ \ensuremath{\ensuremath{\mathit{i}}}$ and remove it:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}(\ens...
...e}(\mathrm{get\_node}(\ensuremath{\mathit{i}})})\\
\end{flushleft}\end{leftbar}

Again, the only expensive part of this operation is finding the $ \ensuremath{\ensuremath{\mathit{i}}}$th node using $ \ensuremath{\mathrm{get\_node}(\ensuremath{\mathit{i}})}$, so $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ runs in $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}, \ensuremath{\ensu...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$ time.

3.2.2 Summary

The following theorem summarizes the performance of a DLList:

Theorem 3..2   A DLList implements the List interface. In this implementation, the $ \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}})}$ operations run in $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensur...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$ time per operation.

It is worth noting that, if we ignore the cost of the $ \ensuremath{\mathrm{get\_node}(\ensuremath{\mathit{i}})}$ operation, then all operations on a DLList take constant time. Thus, the only expensive part of operations on a DLList is finding the relevant node. Once we have the relevant node, adding, removing, or accessing the data at that node takes only constant time.

This is in sharp contrast to the array-based List implementations of Chapter 2; in those implementations, the relevant array item can be found in constant time. However, addition or removal requires shifting elements in the array and, in general, takes non-constant time.

For this reason, linked list structures are well-suited to applications where references to list nodes can be obtained through external means.

opendatastructures.org

5 . 2 LinearHashTable: Linear Probing

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


5.2 LinearHashTable: Linear Probing

The ChainedHashTable data structure uses an array of lists, where the $ \ensuremath{\ensuremath{\mathit{i}}}$th list stores all elements $ \ensuremath{\ensuremath{\mathit{x}}}$ such that $ \ensuremath{\ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}}=\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}$. An alternative, called open addressing is to store the elements directly in an array, $ \ensuremath{\ensuremath{\mathit{t}}}$, with each array location in $ \ensuremath{\ensuremath{\mathit{t}}}$ storing at most one value. This approach is taken by the LinearHashTable described in this section. In some places, this data structure is described as open addressing with linear probing.

The main idea behind a LinearHashTable is that we would, ideally, like to store the element $ \ensuremath{\ensuremath{\mathit{x}}}$ with hash value $ \ensuremath{\ensuremath{\mathit{i}}\gets \ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}}$ in the table location $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$. If we cannot do this (because some element is already stored there) then we try to store it at location $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}[(\ensuremath{\ensuremath{\en...
...}}}}+1)\bmod\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}]$; if that's not possible, then we try $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}[(\ensuremath{\ensuremath{\en...
...}}}}+2)\bmod\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}]$, and so on, until we find a place for $ \ensuremath{\ensuremath{\mathit{x}}}$.

There are three types of entries stored in $ \ensuremath{\ensuremath{\mathit{t}}}$:

  1. data values: actual values in the USet that we are representing;
  2. $ \ensuremath{\ensuremath{\mathit{nil}}}$ values: at array locations where no data has ever been stored; and
  3. $ \ensuremath{\ensuremath{\mathit{del}}}$ values: at array locations where data was once stored but that has since been deleted.
In addition to the counter, $ \ensuremath{\ensuremath{\mathit{n}}}$, that keeps track of the number of elements in the LinearHashTable, a counter, $ \ensuremath{\ensuremath{\mathit{q}}}$, keeps track of the number of elements of Types 1 and 3. That is, $ \ensuremath{\ensuremath{\mathit{q}}}$ is equal to $ \ensuremath{\ensuremath{\mathit{n}}}$ plus the number of $ \ensuremath{\ensuremath{\mathit{del}}}$ values in $ \ensuremath{\ensuremath{\mathit{t}}}$. To make this work efficiently, we need $ \ensuremath{\ensuremath{\mathit{t}}}$ to be considerably larger than $ \ensuremath{\ensuremath{\mathit{q}}}$, so that there are lots of $ \ensuremath{\ensuremath{\mathit{nil}}}$ values in $ \ensuremath{\ensuremath{\mathit{t}}}$. The operations on a LinearHashTable therefore maintain the invariant that $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}\ge 2\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}$.

To summarize, a LinearHashTable contains an array, $ \ensuremath{\ensuremath{\mathit{t}}}$, that stores data elements, and integers $ \ensuremath{\ensuremath{\mathit{n}}}$ and $ \ensuremath{\ensuremath{\mathit{q}}}$ that keep track of the number of data elements and non- $ \ensuremath{\ensuremath{\mathit{nil}}}$ values of $ \ensuremath{\ensuremath{\mathit{t}}}$, respectively. Because many hash functions only work for table sizes that are a power of 2, we also keep an integer $ \ensuremath{\ensuremath{\mathit{d}}}$ and maintain the invariant that $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}=2^\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}$.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{initialize}(...
...th{\ensuremath{\mathit{n}} \gets \ensuremath{0}}\\
\end{flushleft}\end{leftbar}

The $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation in a LinearHashTable is simple. We start at array entry $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$ where $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}=\ensuremath{\ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}}$ and search entries $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$, $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}[(\ensuremath{\ensuremath{\en...
...}}}+1)\bmod \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}]$, $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}[(\ensuremath{\ensuremath{\en...
...}}}+2)\bmod \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}]$, and so on, until we find an index $ \ensuremath{i}'$ such that, either, $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{i}']\gets \ensuremath{x}}$, or $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{i}']\gets \ensuremath{nil}}$. In the former case we return $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}']}$. In the latter case, we conclude that $ \ensuremath{\ensuremath{\mathit{x}}}$ is not contained in the hash table and return $ \ensuremath{\ensuremath{\mathit{nil}}}$.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{find}(\ensur...
...\bmod \mathrm{length}(\ensuremath{\mathit{t}})}}\\
\end{flushleft}\end{leftbar}

The $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation is also fairly easy to implement. After checking that $ \ensuremath{\ensuremath{\mathit{x}}}$ is not already stored in the table (using $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$), we search $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$, $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}[(\ensuremath{\ensuremath{\en...
...}}}+1)\bmod \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}]$, $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}[(\ensuremath{\ensuremath{\en...
...}}}+2)\bmod \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}]$, and so on, until we find a $ \ensuremath{\ensuremath{\mathit{nil}}}$ or $ \ensuremath{\ensuremath{\mathit{del}}}$ and store $ \ensuremath{\ensuremath{\mathit{x}}}$ at that location, increment $ \ensuremath{\ensuremath{\mathit{n}}}$, and $ \ensuremath{\ensuremath{\mathit{q}}}$, if appropriate.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
...return}} \ensuremath{\ensuremath{\mathit{true}}}\\
\end{flushleft}\end{leftbar}

By now, the implementation of the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation should be obvious. We search $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$, $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}[(\ensuremath{\ensuremath{\en...
...}}}+1)\bmod \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}]$, $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}[(\ensuremath{\ensuremath{\en...
...}}}+2)\bmod
\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}]$, and so on until we find an index $ \ensuremath{i}'$ such that $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{i}']\gets \ensuremath{x}}$ or $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{i}']\gets \ensuremath{nil}}$. In the former case, we set $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{i}']\gets \ensuremath{del}}$ and return $ \ensuremath{\ensuremath{\mathit{true}}}$. In the latter case we conclude that $ \ensuremath{\ensuremath{\mathit{x}}}$ was not stored in the table (and therefore cannot be deleted) and return $ \ensuremath{\ensuremath{\mathit{false}}}$.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}(\ens...
...{return}} \ensuremath{\ensuremath{\mathit{nil}}}\\
\end{flushleft}\end{leftbar}

The correctness of the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ methods is easy to verify, though it relies on the use of $ \ensuremath{\ensuremath{\mathit{del}}}$ values. Notice that none of these operations ever sets a non- $ \ensuremath{\ensuremath{\mathit{nil}}}$ entry to $ \ensuremath{\ensuremath{\mathit{nil}}}$. Therefore, when we reach an index $ \ensuremath{i}'$ such that $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{i}']\gets \ensuremath{nil}}$, this is a proof that the element, $ \ensuremath{\ensuremath{\mathit{x}}}$, that we are searching for is not stored in the table; $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}']}$ has always been $ \ensuremath{\ensuremath{\mathit{nil}}}$, so there is no reason that a previous $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation would have proceeded beyond index $ \ensuremath{i}'$.

The $ \ensuremath{\mathrm{resize}()}$ method is called by $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ when the number of non- $ \ensuremath{\ensuremath{\mathit{nil}}}$ entries exceeds $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}/2$ or by $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ when the number of data entries is less than $ \ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})/8}$. The $ \ensuremath{\mathrm{resize}()}$ method works like the $ \ensuremath{\mathrm{resize}()}$ methods in other array-based data structures. We find the smallest non-negative integer $ \ensuremath{\ensuremath{\mathit{d}}}$ such that $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}
\ge 3\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$. We reallocate the array $ \ensuremath{\ensuremath{\mathit{t}}}$ so that it has size $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$, and then we insert all the elements in the old version of $ \ensuremath{\ensuremath{\mathit{t}}}$ into the newly-resized copy of $ \ensuremath{\ensuremath{\mathit{t}}}$. While doing this, we reset $ \ensuremath{\ensuremath{\mathit{q}}}$ equal to $ \ensuremath{\ensuremath{\mathit{n}}}$ since the newly-allocated $ \ensuremath{\ensuremath{\mathit{t}}}$ contains no $ \ensuremath{\ensuremath{\mathit{del}}}$ values.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{resize}()}\\...
...mathit{t}}[\ensuremath{i}] \gets \ensuremath{x}}\\
\end{flushleft}\end{leftbar}

5.2.1 Analysis of Linear Probing

Notice that each operation, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$, or $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$, finishes as soon as (or before) it discovers the first $ \ensuremath{\ensuremath{\mathit{nil}}}$ entry in $ \ensuremath{\ensuremath{\mathit{t}}}$. The intuition behind the analysis of linear probing is that, since at least half the elements in $ \ensuremath{\ensuremath{\mathit{t}}}$ are equal to $ \ensuremath{\ensuremath{\mathit{nil}}}$, an operation should not take long to complete because it will very quickly come across a $ \ensuremath{\ensuremath{\mathit{nil}}}$ entry. We shouldn't rely too heavily on this intuition, though, because it would lead us to (the incorrect) conclusion that the expected number of locations in $ \ensuremath{\ensuremath{\mathit{t}}}$ examined by an operation is at most 2.

For the rest of this section, we will assume that all hash values are independently and uniformly distributed in $ \{0,\ldots,\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}-1\}$. This is not a realistic assumption, but it will make it possible for us to analyze linear probing. Later in this section we will describe a method, called tabulation hashing, that produces a hash function that is ``good enough'' for linear probing. We will also assume that all indices into the positions of $ \ensuremath{\ensuremath{\mathit{t}}}$ are taken modulo $ \ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}$, so that $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$ is really a shorthand for $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}[\ensuremath{\ensuremath{\ens...
...t{i}}}}\bmod\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}]$.

We say that a run of length $ k$ that starts at $ \ensuremath{\ensuremath{\mathit{i}}}$ occurs when all the table entries $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}}, \e...
...ensuremath{\mathit{t}}}}[\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+k-1]$ are non- $ \ensuremath{\ensuremath{\mathit{nil}}}$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}[\ensuremath{\ensuremath{\ens...
...ensuremath{\mathit{i}}}}+k]=\ensuremath{\ensuremath{\ensuremath{\mathit{nil}}}}$. The number of non- $ \ensuremath{\ensuremath{\mathit{nil}}}$ elements of $ \ensuremath{\ensuremath{\mathit{t}}}$ is exactly $ \ensuremath{\ensuremath{\mathit{q}}}$ and the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ method ensures that, at all times, $ \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}\le\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}/2$. There are $ \ensuremath{\ensuremath{\mathit{q}}}$ elements $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_1,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}}$ that have been inserted into $ \ensuremath{\ensuremath{\mathit{t}}}$ since the last $ \ensuremath{\mathrm{rebuild}()}$ operation. By our assumption, each of these has a hash value, $ \ensuremath{\ensuremath{\ensuremath{\mathit{hash}}}}(\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_j)$, that is uniform and independent of the rest. With this setup, we can prove the main lemma required to analyze linear probing.

Lemma 5..4   Fix a value $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\in\{0,\ldots,\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}-1\}$. Then the probability that a run of length $ k$ starts at $ \ensuremath{\ensuremath{\mathit{i}}}$ is $ O(c^k)$ for some constant $ 0<c<1$.

Proof. If a run of length $ k$ starts at $ \ensuremath{\ensuremath{\mathit{i}}}$, then there are exactly $ k$ elements $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_j$ such that $ \ensuremath{\ensuremath{\ensuremath{\mathit{hash}}}}(\ensuremath{\ensuremath{\...
...th{\mathit{i}}}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+k-1\}$. The probability that this occurs is exactly

$\displaystyle p_k = \binom{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}}{k...
...}})}}}\right)^{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}-k} \enspace ,
$

since, for each choice of $ k$ elements, these $ k$ elements must hash to one of the $ k$ locations and the remaining $ \ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}-k$ elements must hash to the other $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}-k$ table locations.5.2

In the following derivation we will cheat a little and replace $ r!$ with $ (r/e)^r$. Stirling's Approximation (Section 1.3.2) shows that this is only a factor of $ O(\sqrt{r})$ from the truth. This is just done to make the derivation simpler; Exercise 5.4 asks the reader to redo the calculation more rigorously using Stirling's Approximation in its entirety.

The value of $ p_k$ is maximized when $ \ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}$ is minimum, and the data structure maintains the invariant that $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}} \ge 2\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}$, so

$\displaystyle p_k$ $\displaystyle \le \binom{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}}{k}\...
...ath{\mathit{q}}}}}\right)^{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}-k}$    
  $\displaystyle = \left(\frac{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}!}...
...ath{\mathit{q}}}}}\right)^{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}-k}$    
  $\displaystyle \approx \left(\frac{\ensuremath{\ensuremath{\ensuremath{\mathit{q...
...ath{\mathit{q}}}}}\right)^{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}-k}$   [Stirling's approximation]    
  $\displaystyle = \left(\frac{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}^{...
...ath{\mathit{q}}}}}\right)^{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}-k}$    
  $\displaystyle = \left(\frac{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}k}...
...{\mathit{q}}}}-k)}\right)^{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}-k}$    
  $\displaystyle = \left(\frac{1}{2}\right)^k \left(\frac{(2\ensuremath{\ensuremat...
...{\mathit{q}}}}-k)}\right)^{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}-k}$    
  $\displaystyle = \left(\frac{1}{2}\right)^k \left(1+\frac{k}{2(\ensuremath{\ensu...
...{\mathit{q}}}}-k)}\right)^{\ensuremath{\ensuremath{\ensuremath{\mathit{q}}}}-k}$    
  $\displaystyle \le \left(\frac{\sqrt{e}}{2}\right)^k \enspace .$    

(In the last step, we use the inequality $ (1+1/x)^x \le e$, which holds for all $ x>0$.) Since $ \sqrt{e}/{2}< 0.824360636 < 1$, this completes the proof. $ \qedsymbol$

Using Lemma 5.4 to prove upper-bounds on the expected running time of $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ is now fairly straightforward. Consider the simplest case, where we execute $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ for some value $ \ensuremath{\ensuremath{\mathit{x}}}$ that has never been stored in the LinearHashTable. In this case, $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}=\ensuremath{\ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}}$ is a random value in $ \{0,\ldots,\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}-1\}$ independent of the contents of $ \ensuremath{\ensuremath{\mathit{t}}}$. If $ \ensuremath{\ensuremath{\mathit{i}}}$ is part of a run of length $ k$, then the time it takes to execute the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation is at most $ O(1+k)$. Thus, the expected running time can be upper-bounded by

$\displaystyle O\left(1 + \left(\frac{1}{\ensuremath{\ensuremath{\mathrm{length}...
...{\ensuremath{\mathit{i}}}} is part of a run of length $k$}\}\right) \enspace .
$

Note that each run of length $ k$ contributes to the inner sum $ k$ times for a total contribution of $ k^2$, so the above sum can be rewritten as

  $\displaystyle { } O\left(1 + \left(\frac{1}{\ensuremath{\ensuremath{\mathrm{len...
...math{\ensuremath{\ensuremath{\mathit{i}}}} starts a run of length $k$}\}\right)$    
  $\displaystyle \le O\left(1 + \left(\frac{1}{\ensuremath{\ensuremath{\mathrm{len...
...th{\mathrm{length}(\ensuremath{\mathit{t}})}}}\sum_{k=0}^{\infty} k^2p_k\right)$    
  $\displaystyle = O\left(1 + \sum_{k=0}^{\infty} k^2p_k\right)$    
  $\displaystyle = O\left(1 + \sum_{k=0}^{\infty} k^2\cdot O(c^k)\right)$    
  $\displaystyle = O(1) \enspace .$    

The last step in this derivation comes from the fact that $ \sum_{k=0}^{\infty} k^2\cdot O(c^k)$ is an exponentially decreasing series.5.3Therefore, we conclude that the expected running time of the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation for a value $ \ensuremath{\ensuremath{\mathit{x}}}$ that is not contained in a LinearHashTable is $ O(1)$.

If we ignore the cost of the $ \ensuremath{\mathrm{resize}()}$ operation, then the above analysis gives us all we need to analyze the cost of operations on a LinearHashTable.

First of all, the analysis of $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ given above applies to the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation when $ \ensuremath{\ensuremath{\mathit{x}}}$ is not contained in the table. To analyze the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation when $ \ensuremath{\ensuremath{\mathit{x}}}$ is contained in the table, we need only note that this is the same as the cost of the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation that previously added $ \ensuremath{\ensuremath{\mathit{x}}}$ to the table. Finally, the cost of a $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation is the same as the cost of a $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation.

In summary, if we ignore the cost of calls to $ \ensuremath{\mathrm{resize}()}$, all operations on a LinearHashTable run in $ O(1)$ expected time. Accounting for the cost of resize can be done using the same type of amortized analysis performed for the ArrayStack data structure in Section 2.1.

5.2.2 Summary

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

Theorem 5..2   A LinearHashTable implements the USet interface. Ignoring the cost of calls to $ \ensuremath{\mathrm{resize}()}$, a LinearHashTable supports the operations $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ in $ O(1)$ expected time per operation.

Furthermore, beginning with an empty LinearHashTable, any sequence of $ m$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations results in a total of $ O(m)$ time spent during all calls to $ \ensuremath{\mathrm{resize}()}$.


5.2.3 Tabulation Hashing

While analyzing the LinearHashTable structure, we made a very strong assumption: That for any set of elements, $ \{\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_1,\ldots,\ensuremath{\ensu...
...h{\ensuremath{\mathit{x}}}}_\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\}$, the hash values $ \ensuremath{\ensuremath{\ensuremath{\mathit{hash}}}}($x $ _1),\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{hash}}}}(\ensuremath{\e...
...th{\ensuremath{\mathit{x}}}}_\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ are independently and uniformly distributed over the set $ \{0,\ldots,\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}-1\}$. One way to achieve this is to store a giant array, $ \ensuremath{\ensuremath{\mathit{tab}}}$, of length $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$, where each entry is a random $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integer, independent of all the other entries. In this way, we could implement $ \ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}$ by extracting a $ \ensuremath{\ensuremath{\mathit{d}}}$-bit integer from $ \ensuremath{\ensuremath{\mathit{tab}}[\ensuremath{\mathit{x}}.\mathrm{hash\_code}()]}$:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{ideal\_hash}...
...ensuremath{\mathit{w}}-\ensuremath{\mathit{d}}]}\\
\end{flushleft}\end{leftbar}
Here, $ \ensuremath{\gg}$, is the bitwise right shift operator, so $ \ensuremath{\ensuremath{\mathit{x}}.\mathrm{hash\_code}() \ensuremath{\gg} \ensuremath{\mathit{w}}-\ensuremath{\mathit{d}}}$ extracts the $ \ensuremath{\ensuremath{\mathit{d}}}$ most significant bits of $ \ensuremath{\ensuremath{\mathit{x}}}$'s $ \ensuremath{\ensuremath{\mathit{w}}}$-bit hash code.

Unfortunately, storing an array of size $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ is prohibitive in terms of memory usage. The approach used by tabulation hashing is to, instead, treat $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers as being comprised of $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}/\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}$ integers, each having only $ \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}$ bits. In this way, tabulation hashing only needs $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}/\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}$ arrays each of length $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}}$. All the entries in these arrays are independent random $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers. To obtain the value of $ \ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}$ we split $ \ensuremath{\ensuremath{\mathit{x}}.\mathrm{hash\_code}()}$ up into $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}/\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}$ $ \ensuremath{\ensuremath{\mathit{r}}}$-bit integers and use these as indices into these arrays. We then combine all these values with the bitwise exclusive-or operator to obtain $ \ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}$. The following code shows how this works when $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}=32$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}=4$:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{hash}(\ensur...
...ensuremath{\mathit{w}}-\ensuremath{\mathit{d}})}\\
\end{flushleft}\end{leftbar}
In this case, $ \ensuremath{\ensuremath{\mathit{tab}}}$ is a two-dimensional array with four columns and $ 2^{32/4}=256$ rows. Quantities like $ \ensuremath{\mathrm{ff}_{16}}$, used above, are hexadecimal numbers whose digits have 16 possible values 0-9, which have their usual meaning and a-f, which denote 10-15. The number $ \ensuremath{\ensuremath{\mathrm{ff}_{16}}}=15\cdot 16 + 15 = 255$. The $ \wedge $ symbol is the bitwise and operator, so code like $ \ensuremath{\ensuremath{\mathit{h}} \ensuremath{\gg} 8 \wedge \mathrm{ff}_{16}}$ extracts bits with index 8 through 15 of $ \ensuremath{\ensuremath{\mathit{h}}}$.

One can easily verify that, for any $ \ensuremath{\ensuremath{\mathit{x}}}$, $ \ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}$ is uniformly distributed over $ \{0,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}-1\}$. With a little work, one can even verify that any pair of values have independent hash values. This implies tabulation hashing could be used in place of multiplicative hashing for the ChainedHashTable implementation.

However, it is not true that any set of $ \ensuremath{\ensuremath{\mathit{n}}}$ distinct values gives a set of $ \ensuremath{\ensuremath{\mathit{n}}}$ independent hash values. Nevertheless, when tabulation hashing is used, the bound of Theorem 5.2 still holds. References for this are provided at the end of this chapter.



Footnotes

... locations.5.2
Note that $ p_k$ is greater than the probability that a run of length $ k$ starts at $ \ensuremath{\ensuremath{\mathit{i}}}$, since the definition of $ p_k$ does not include the requirement $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}[\ensuremath{\ensuremath{\ens...
...ensuremath{\mathit{i}}}}+k]=\ensuremath{\ensuremath{\ensuremath{\mathit{nil}}}}$.
... series.5.3
In the terminology of many calculus texts, this sum passes the ratio test: There exists a positive integer $ k_0$ such that, for all $ k\ge k_0$, $ \frac{(k+1)^2c^{k+1}}{k^2c^k} < 1$.
opendatastructures.org

10 . 3 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.

10.3 Discussion and Exercises

The implicit representation of a complete binary tree as an array, or list, seems to have been first proposed by Eytzinger [27]. He used this representation in books containing pedigree family trees of noble families. The BinaryHeap data structure described here was first introduced by Williams [76].

The randomized MeldableHeap data structure described here appears to have first been proposed by Gambin and Malinowski [34]. Other meldable heap implementations exist, including leftist heaps [16,48, Section 5.3.2], binomial heaps [73], Fibonacci heaps [30], pairing heaps [29], and skew heaps [70], although none of these are as simple as the MeldableHeap structure.

Some of the above structures also support a $ \ensuremath{\mathrm{decrease\_key}(\ensuremath{\mathit{u}},\ensuremath{\mathit{y}})}$ operation in which the value stored at node $ \ensuremath{\ensuremath{\mathit{u}}}$ is decreased to $ \ensuremath{\ensuremath{\mathit{y}}}$. (It is a pre-condition that $ \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}\le\ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{x}}}}$.) In most of the preceding structures, this operation can be supported in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time by removing node $ \ensuremath{\ensuremath{\mathit{u}}}$ and adding $ \ensuremath{\ensuremath{\mathit{y}}}$. However, some of these structures can implement $ \ensuremath{\mathrm{decrease\_key}(\ensuremath{\mathit{u}},\ensuremath{\mathit{y}})}$ more efficiently. In particular, $ \ensuremath{\mathrm{decrease\_key}(\ensuremath{\mathit{u}},\ensuremath{\mathit{y}})}$ takes $ O(1)$ amortized time in Fibonacci heaps and $ O(\log\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ amortized time in a special version of pairing heaps [25]. This more efficient $ \ensuremath{\mathrm{decrease\_key}(\ensuremath{\mathit{u}},\ensuremath{\mathit{y}})}$ operation has applications in speeding up several graph algorithms, including Dijkstra's shortest path algorithm [30].

Exercise 10..1   Illustrate the addition of the values 7 and then 3 to the BinaryHeap shown at the end of Figure 10.2.

Exercise 10..2   Illustrate the removal of the next two values (6 and 8) on the BinaryHeap shown at the end of Figure 10.3.

Exercise 10..3   Implement the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ method, that removes the value stored in $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$ in a BinaryHeap. This method should run in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time. Next, explain why this method is not likely to be useful.

Exercise 10..4   A $ d$-ary tree is a generalization of a binary tree in which each internal node has $ d$ children. Using Eytzinger's method it is also possible to represent complete $ d$-ary trees using arrays. Work out the equations that, given an index $ \ensuremath{\ensuremath{\mathit{i}}}$, determine the index of $ \ensuremath{\ensuremath{\mathit{i}}}$'s parent and each of $ \ensuremath{\ensuremath{\mathit{i}}}$'s $ d$ children in this representation.

Exercise 10..5   Using what you learned in Exercise 10.4, design and implement a DaryHeap, the $ d$-ary generalization of a BinaryHeap. Analyze the running times of operations on a DaryHeap and test the performance of your DaryHeap implementation against that of the BinaryHeap implementation given here.

Exercise 10..6   Illustrate the addition of the values 17 and then 82 in the MeldableHeap $ \ensuremath{\ensuremath{\mathit{h_1}}}$ shown in Figure 10.4. Use a coin to simulate a random bit when needed.

Exercise 10..7   Illustrate the removal of the next two values (4 and 8) in the MeldableHeap $ \ensuremath{\ensuremath{\mathit{h_1}}}$ shown in Figure 10.4. Use a coin to simulate a random bit when needed.

Exercise 10..8   Implement the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{u}})}$ method, that removes the node $ \ensuremath{\ensuremath{\mathit{u}}}$ from a MeldableHeap. This method should run in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time.

Exercise 10..9   Show how to find the second smallest value in a BinaryHeap or MeldableHeap in constant time.

Exercise 10..10   Show how to find the $ k$th smallest value in a BinaryHeap or MeldableHeap in $ O(k\log k)$ time. (Hint: Using another heap might help.)

Exercise 10..11   Suppose you are given $ \ensuremath{\ensuremath{\mathit{k}}}$ sorted lists, of total length $ \ensuremath{\ensuremath{\mathit{n}}}$. Using a heap, show how to merge these into a single sorted list in $ O(n\log
k)$ time. (Hint: Starting with the case $ k=2$ can be instructive.)

opendatastructures.org

14 . 3 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.

14.3 Discussion and Exercises

The external memory model of computation was introduced by Aggarwal and Vitter [4]. It is sometimes also called the I/O model or the disk access model.

$ B$-Trees are to external memory searching what binary search trees are to internal memory searching. $ B$-trees were introduced by Bayer and McCreight [9] in 1970 and, less than ten years later, the title of Comer's ACM Computing Surveys article referred to them as ubiquitous [15].

Like binary search trees, there are many variants of $ B$-Trees, including $ B^+$-trees, $ B^*$-trees, and counted $ B$-trees. $ B$-trees are indeed ubiquitous and are the primary data structure in many file systems, including Apple's HFS+, Microsoft's NTFS, and Linux's Ext4; every major database system; and key-value stores used in cloud computing. Graefe's recent survey [36] provides a 200+ page overview of the many modern applications, variants, and optimizations of $ B$-trees.

$ B$-trees implement the SSet interface. If only the USet interface is needed, then external memory hashing could be used as an alternative to $ B$-trees. External memory hashing schemes do exist; see, for example, Jensen and Pagh [43]. These schemes implement the USet operations in $ O(1)$ expected time in the external memory model. However, for a variety of reasons, many applications still use $ B$-trees even though they only require USet operations.

One reason $ B$-trees are such a popular choice is that they often perform better than their $ O(\log_B \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ running time bounds suggest. The reason for this is that, in external memory settings, the value of $ B$ is typically quite large--in the hundreds or even thousands. This means that 99% or even 99.9% of the data in a $ B$-tree is stored in the leaves. In a database system with a large memory, it may be possible to cache all the internal nodes of a $ B$-tree in RAM, since they only represent 1% or 0.1% of the total data set. When this happens, this means that a search in a $ B$-tree involves a very fast search in RAM, through the internal nodes, followed by a single external memory access to retrieve a leaf.

Exercise 14..1   Show what happens when the keys 1.5 and then 7.5 are added to the $ B$-tree in Figure 14.2.

Exercise 14..2   Show what happens when the keys 3 and then 4 are removed from the $ B$-tree in Figure 14.2.

Exercise 14..3   What is the maximum number of internal nodes in a $ B$-tree that stores $ \ensuremath{\ensuremath{\mathit{n}}}$ keys (as a function of $ \ensuremath{\ensuremath{\mathit{n}}}$ and $ B$)?

Exercise 14..4   The introduction to this chapter claims that $ B$-trees only need an internal memory of size $ O(B+\log_B\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$. However, the implementation given here actually requires more memory.
  1. Show that the implementation of the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ methods given in this chapter use an internal memory proportional to $ B\log_B \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$.
  2. Describe how these methods could be modified in order to reduce their memory consumption to $ O(B + \log_B \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$.

Exercise 14..5   Draw the credits used in the proof of Lemma 14.1 on the trees in Figures 14.6 and 14.7. Verify that (with three additional credits) it is possible to pay for the splits, merges, and borrows and maintain the credit invariant.

Exercise 14..6   Design a modified version of a $ B$-tree in which nodes can have anywhere from $ B$ up to $ 3B$ children (and hence $ B-1$ up to $ 3B-1$ keys). Show that this new version of $ B$-trees performs only $ O(m/B)$ splits, merges, and borrows during a sequence of $ m$ operations. (Hint: For this to work, you will have to be more agressive with merging, sometimes merging two nodes before it is strictly necessary.)

Exercise 14..7   In this exercise, you will design a modified method of splitting and merging in $ B$-trees that asymptotically reduces the number of splits, borrows and merges by considering up to three nodes at a time.
  1. Let $ \ensuremath{\ensuremath{\mathit{u}}}$ be an overfull node and let $ \ensuremath{\ensuremath{\mathit{v}}}$ be a sibling immediately to the right of $ \ensuremath{\ensuremath{\mathit{u}}}$. There are two ways to fix the overflow at $ \ensuremath{\ensuremath{\mathit{u}}}$:
    1. $ \ensuremath{\ensuremath{\mathit{u}}}$ can give some of its keys to $ \ensuremath{\ensuremath{\mathit{v}}}$; or
    2. $ \ensuremath{\ensuremath{\mathit{u}}}$ can be split and the keys of $ \ensuremath{\ensuremath{\mathit{u}}}$ and $ \ensuremath{\ensuremath{\mathit{v}}}$ can be evenly distributed among $ \ensuremath{\ensuremath{\mathit{u}}}$, $ \ensuremath{\ensuremath{\mathit{v}}}$, and the newly created node, $ \ensuremath{\ensuremath{\mathit{w}}}$.
    Show that this can always be done in such a way that, after the operation, each of the (at most 3) affected nodes has at least $ B+\alpha B$ keys and at most $ 2B-\alpha B$ keys, for some constant $ \alpha > 0$.
  2. Let $ \ensuremath{\ensuremath{\mathit{u}}}$ be an underfull node and let $ \ensuremath{\ensuremath{\mathit{v}}}$ and $ \ensuremath{\ensuremath{\mathit{w}}}$ be siblings of $ \ensuremath{\ensuremath{\mathit{u}}}$ There are two ways to fix the underflow at $ \ensuremath{\ensuremath{\mathit{u}}}$:
    1. keys can be redistributed among $ \ensuremath{\ensuremath{\mathit{u}}}$, $ \ensuremath{\ensuremath{\mathit{v}}}$, and $ \ensuremath{\ensuremath{\mathit{w}}}$; or
    2. $ \ensuremath{\ensuremath{\mathit{u}}}$, $ \ensuremath{\ensuremath{\mathit{v}}}$, and $ \ensuremath{\ensuremath{\mathit{w}}}$ can be merged into two nodes and the keys of $ \ensuremath{\ensuremath{\mathit{u}}}$, $ \ensuremath{\ensuremath{\mathit{v}}}$, and $ \ensuremath{\ensuremath{\mathit{w}}}$ can be redistributed amongst these nodes.
    Show that this can always be done in such a way that, after the operation, each of the (at most 3) affected nodes has at least $ B+\alpha B$ keys and at most $ 2B-\alpha B$ keys, for some constant $ \alpha > 0$.
  3. Show that, with these modifications, the number of merges, borrows, and splits that occur during $ m$ operations is $ O(m/B)$.

Exercise 14..8   A $ B^+$-tree, illustrated in Figure 14.11 stores every key in a leaf and keeps its leaves stored as a doubly-linked list. As usual, each leaf stores between $ B-1$ and $ 2B-1$ keys. Above this list is a standard $ B$-tree that stores the largest value from each leaf but the last.
  1. Describe fast implementations of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ in a $ B^+$-tree.
  2. Explain how to efficiently implement the $ \ensuremath{\mathrm{find\_range}(\ensuremath{\mathit{x}},\ensuremath{\mathit{y}})}$ method, that reports all values greater than $ \ensuremath{\ensuremath{\mathit{x}}}$ and less than or equal to $ \ensuremath{\ensuremath{\mathit{y}}}$, in a $ B^+$-tree.
  3. Implement a class, BPlusTree, that implements $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{find\_range}(\ensuremath{\mathit{x}},\ensuremath{\mathit{y}})}$.
  4. $ B^+$-trees duplicate some of the keys because they are stored both in the $ B$-tree and in the list. Explain why this duplication does not add up to much for large values of $ B$.

Figure 14.11: A $ B^+$-tree is a $ B$-tree on top of a doubly-linked list of blocks.
\includegraphics[width=\textwidth ]{figs-python/bplustree}

opendatastructures.org

Using promises

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.

Using promises

A Promise is an object representing the eventual completion or failure of an asynchronous operation. Since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them.

Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. Imagine a function, createAudioFileAsync(), which asynchronously generates a sound file given a configuration record and two callback functions: one called if the audio file is successfully created, and the other called if an error occurs.

Here's some code that uses createAudioFileAsync():

js
function successCallback(result) {
  console.log(`Audio file ready at URL: ${result}`);
}

function failureCallback(error) {
  console.error(`Error generating audio file: ${error}`);
}

createAudioFileAsync(audioSettings, successCallback, failureCallback);

If createAudioFileAsync() were rewritten to return a promise, you would attach your callbacks to it instead:

js
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);

This convention has several advantages. We will explore each one.

Chaining

A common need is to execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds, with the result from the previous step. In the old days, doing several asynchronous operations in a row would lead to the classic callback hell:

js
doSomething(function (result) {
  doSomethingElse(result, function (newResult) {
    doThirdThing(newResult, function (finalResult) {
      console.log(`Got the final result: ${finalResult}`);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

With promises, we accomplish this by creating a promise chain. The API design of promises makes this great, because callbacks are attached to the returned promise object, instead of being passed into a function.

Here's the magic: the then() function returns a new promise, different from the original:

js
const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);

This second promise (promise2) represents the completion not just of doSomething(), but also of the successCallback or failureCallback you passed in — which can be other asynchronous functions returning a promise. When that's the case, any callbacks added to promise2 get queued behind the promise returned by either successCallback or failureCallback.

Note: If you want a working example to play with, you can use the following template to create any function returning a promise:

js
function doSomething() {
  return new Promise((resolve) => {
    setTimeout(() => {
      // Other things to do before completion of the promise
      console.log("Did something");
      // The fulfillment value of the promise
      resolve("https://example.com/");
    }, 200);
  });
}

The implementation is discussed in the Creating a Promise around an old callback API section below.

With this pattern, you can create longer chains of processing, where each promise represents the completion of one asynchronous step in the chain. In addition, the arguments to then are optional, and catch(failureCallback) is short for then(null, failureCallback) — so if your error handling code is the same for all steps, you can attach it to the end of the chain:

js
doSomething()
  .then(function (result) {
    return doSomethingElse(result);
  })
  .then(function (newResult) {
    return doThirdThing(newResult);
  })
  .then(function (finalResult) {
    console.log(`Got the final result: ${finalResult}`);
  })
  .catch(failureCallback);

You might see this expressed with arrow functions instead:

js
doSomething()
  .then((result) => doSomethingElse(result))
  .then((newResult) => doThirdThing(newResult))
  .then((finalResult) => {
    console.log(`Got the final result: ${finalResult}`);
  })
  .catch(failureCallback);

Note: Arrow function expressions can have an implicit return; so, () => x is short for () => { return x; }.

doSomethingElse and doThirdThing can return any value — if they return promises, that promise is first waited until it settles, and the next callback receives the fulfillment value, not the promise itself. It is important to always return promises from then callbacks, even if the promise always resolves to undefined. If the previous handler started a promise but did not return it, there's no way to track its settlement anymore, and the promise is said to be "floating".

js
doSomething()
  .then((url) => {
    // Missing `return` keyword in front of fetch(url).
    fetch(url);
  })
  .then((result) => {
    // result is undefined, because nothing is returned from the previous
    // handler. There's no way to know the return value of the fetch()
    // call anymore, or whether it succeeded at all.
  });

By returning the result of the fetch call (which is a promise), we can both track its completion and receive its value when it completes.

js
doSomething()
  .then((url) => {
    // `return` keyword added
    return fetch(url);
  })
  .then((result) => {
    // result is a Response object
  });

Floating promises could be worse if you have race conditions — if the promise from the last handler is not returned, the next then handler will be called early, and any value it reads may be incomplete.

js
const listOfIngredients = [];

doSomething()
  .then((url) => {
    // Missing `return` keyword in front of fetch(url).
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        listOfIngredients.push(data);
      });
  })
  .then(() => {
    console.log(listOfIngredients);
    // listOfIngredients will always be [], because the fetch request hasn't completed yet.
  });

Therefore, as a rule of thumb, whenever your operation encounters a promise, return it and defer its handling to the next then handler.

js
const listOfIngredients = [];

doSomething()
  .then((url) => {
    // `return` keyword now included in front of fetch call.
    return fetch(url)
      .then((res) => res.json())
      .then((data) => {
        listOfIngredients.push(data);
      });
  })
  .then(() => {
    console.log(listOfIngredients);
    // listOfIngredients will now contain data from fetch call.
  });

Even better, you can flatten the nested chain into a single chain, which is simpler and makes error handling easier. The details are discussed in the Nesting section below.

js
doSomething()
  .then((url) => fetch(url))
  .then((res) => res.json())
  .then((data) => {
    listOfIngredients.push(data);
  })
  .then(() => {
    console.log(listOfIngredients);
  });

Using async/await can help you write code that's more intuitive and resembles synchronous code. Below is the same example using async/await:

js
async function logIngredients() {
  const url = await doSomething();
  const res = await fetch(url);
  const data = await res.json();
  listOfIngredients.push(data);
  console.log(listOfIngredients);
}

Note how the code looks exactly like synchronous code, except for the await keywords in front of promises. One of the only tradeoffs is that it may be easy to forget the await keyword, which can only be fixed when there's a type mismatch (e.g., trying to use a promise as a value).

async/await builds on promises — for example, doSomething() is the same function as before, so there's minimal refactoring needed to change from promises to async/await. You can read more about the async/await syntax in the async functions and await references.

Note: async/await has the same concurrency semantics as normal promise chains. await within one async function does not stop the entire program, only the parts that depend on its value, so other async jobs can still run while the await is pending.

Error handling

You might recall seeing failureCallback three times in the pyramid of doom earlier, compared to only once at the end of the promise chain:

js
doSomething()
  .then((result) => doSomethingElse(result))
  .then((newResult) => doThirdThing(newResult))
  .then((finalResult) => console.log(`Got the final result: ${finalResult}`))
  .catch(failureCallback);

If there's an exception, the browser will look down the chain for .catch() handlers or onRejected. This is very much modeled after how synchronous code works:

js
try {
  const result = syncDoSomething();
  const newResult = syncDoSomethingElse(result);
  const finalResult = syncDoThirdThing(newResult);
  console.log(`Got the final result: ${finalResult}`);
} catch (error) {
  failureCallback(error);
}

This symmetry with asynchronous code culminates in the async/await syntax:

js
async function foo() {
  try {
    const result = await doSomething();
    const newResult = await doSomethingElse(result);
    const finalResult = await doThirdThing(newResult);
    console.log(`Got the final result: ${finalResult}`);
  } catch (error) {
    failureCallback(error);
  }
}

Promises solve a fundamental flaw with the callback pyramid of doom, by catching all errors, even thrown exceptions and programming errors. This is essential for functional composition of asynchronous operations. All errors are now handled by the catch() method at the end of the chain, and you should almost never need to use try/catch without using async/await.

Nesting

In the examples above involving listOfIngredients, the first one has one promise chain nested in the return value of another then() handler, while the second one uses an entirely flat chain. Simple promise chains are best kept flat without nesting, as nesting can be a result of careless composition.

Nesting is a control structure to limit the scope of catch statements. Specifically, a nested catch only catches failures in its scope and below, not errors higher up in the chain outside the nested scope. When used correctly, this gives greater precision in error recovery:

js
doSomethingCritical()
  .then((result) =>
    doSomethingOptional(result)
      .then((optionalResult) => doSomethingExtraNice(optionalResult))
      .catch((e) => {}),
  ) // Ignore if optional stuff fails; proceed.
  .then(() => moreCriticalStuff())
  .catch((e) => console.error(`Critical failure: ${e.message}`));

Note that the optional steps here are nested — with the nesting caused not by the indentation, but by the placement of the outer ( and ) parentheses around the steps.

The inner error-silencing catch handler only catches failures from doSomethingOptional() and doSomethingExtraNice(), after which the code resumes with moreCriticalStuff(). Importantly, if doSomethingCritical() fails, its error is caught by the final (outer) catch only, and does not get swallowed by the inner catch handler.

In async/await, this code looks like:

js
async function main() {
  try {
    const result = await doSomethingCritical();
    try {
      const optionalResult = await doSomethingOptional(result);
      await doSomethingExtraNice(optionalResult);
    } catch (e) {
      // Ignore failures in optional steps and proceed.
    }
    await moreCriticalStuff();
  } catch (e) {
    console.error(`Critical failure: ${e.message}`);
  }
}

Note: If you don't have sophisticated error handling, you very likely don't need nested then handlers. Instead, use a flat chain and put the error handling logic at the end.

Chaining after a catch

It's possible to chain after a failure, i.e., a catch, which is useful to accomplish new actions even after an action failed in the chain. Read the following example:

js
doSomething()
  .then(() => {
    throw new Error("Something failed");

    console.log("Do this");
  })
  .catch(() => {
    console.error("Do that");
  })
  .then(() => {
    console.log("Do this, no matter what happened before");
  });

This will output the following text:

Do that
Do this, no matter what happened before

Note: The text "Do this" is not displayed because the "Something failed" error caused a rejection.

In async/await, this code looks like:

js
async function main() {
  try {
    await doSomething();
    throw new Error("Something failed");
    console.log("Do this");
  } catch (e) {
    console.error("Do that");
  }
  console.log("Do this, no matter what happened before");
}

Promise rejection events

If a promise rejection event is not handled by any handler, it bubbles to the top of the call stack, and the host needs to surface it. On the web, whenever a promise is rejected, one of two events is sent to the global scope (generally, this is either the window or, if being used in a web worker, it's the Worker or other worker-based interface). The two events are:

unhandledrejection

Sent when a promise is rejected but there is no rejection handler available.

rejectionhandled

Sent when a handler is attached to a rejected promise that has already caused an unhandledrejection event.

In both cases, the event (of type PromiseRejectionEvent) has as members a promise property indicating the promise that was rejected, and a reason property that provides the reason given for the promise to be rejected.

These make it possible to offer fallback error handling for promises, as well as to help debug issues with your promise management. These handlers are global per context, so all errors will go to the same event handlers, regardless of source.

In Node.js, handling promise rejection is slightly different. You capture unhandled rejections by adding a handler for the Node.js unhandledRejection event (notice the difference in capitalization of the name), like this:

js
process.on("unhandledRejection", (reason, promise) => {
  // Add code here to examine the "promise" and "reason" values
});

For Node.js, to prevent the error from being logged to the console (the default action that would otherwise occur), adding that process.on() listener is all that's necessary; there's no need for an equivalent of the browser runtime's preventDefault() method.

However, if you add that process.on listener but don't also have code within it to handle rejected promises, they will just be dropped on the floor and silently ignored. So ideally, you should add code within that listener to examine each rejected promise and make sure it was not caused by an actual code bug.

Composition

There are four composition tools for running asynchronous operations concurrently: Promise.all(), Promise.allSettled(), Promise.any(), and Promise.race().

We can start operations at the same time and wait for them all to finish like this:

js
Promise.all([func1(), func2(), func3()]).then(([result1, result2, result3]) => {
  // use result1, result2 and result3
});

If one of the promises in the array rejects, Promise.all() immediately rejects the returned promise. The other operations continue to run, but their outcomes are not available via the return value of Promise.all(). This may cause unexpected state or behavior. Promise.allSettled() is another composition tool that ensures all operations are complete before resolving.

These methods all run promises concurrently — a sequence of promises are started simultaneously and do not wait for each other. Sequential composition is possible using some clever JavaScript:

js
[func1, func2, func3]
  .reduce((p, f) => p.then(f), Promise.resolve())
  .then((result3) => {
    /* use result3 */
  });

In this example, we reduce an array of asynchronous functions down to a promise chain. The code above is equivalent to:

js
Promise.resolve()
  .then(func1)
  .then(func2)
  .then(func3)
  .then((result3) => {
    /* use result3 */
  });

This can be made into a reusable compose function, which is common in functional programming:

js
const applyAsync = (acc, val) => acc.then(val);
const composeAsync =
  (...funcs) =>
  (x) =>
    funcs.reduce(applyAsync, Promise.resolve(x));

The composeAsync() function accepts any number of functions as arguments and returns a new function that accepts an initial value to be passed through the composition pipeline:

js
const transformData = composeAsync(func1, func2, func3);
const result3 = transformData(data);

Sequential composition can also be done more succinctly with async/await:

js
let result;
for (const f of [func1, func2, func3]) {
  result = await f(result);
}
/* use last result (i.e. result3) */

However, before you compose promises sequentially, consider if it's really necessary — it's always better to run promises concurrently so that they don't unnecessarily block each other unless one promise's execution depends on another's result.

Cancellation

Promise itself has no first-class protocol for cancellation, but you may be able to directly cancel the underlying asynchronous operation, typically using AbortController.

Creating a Promise around an old callback API

A Promise can be created from scratch using its constructor. This should be needed only to wrap old APIs.

In an ideal world, all asynchronous functions would already return promises. Unfortunately, some APIs still expect success and/or failure callbacks to be passed in the old way. The most obvious example is the setTimeout() function:

js
setTimeout(() => saySomething("10 seconds passed"), 10 * 1000);

Mixing old-style callbacks and promises is problematic. If saySomething() fails or contains a programming error, nothing catches it. This is intrinsic to the design of setTimeout().

Luckily we can wrap setTimeout() in a promise. The best practice is to wrap the callback-accepting functions at the lowest possible level, and then never call them directly again:

js
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

wait(10 * 1000)
  .then(() => saySomething("10 seconds"))
  .catch(failureCallback);

The promise constructor takes an executor function that lets us resolve or reject a promise manually. Since setTimeout() doesn't really fail, we left out reject in this case. For more information on how the executor function works, see the Promise() reference.

Timing

Lastly, we will look into the more technical details, about when the registered callbacks get called.

Guarantees

In the callback-based API, when and how the callback gets called depends on the API implementor. For example, the callback may be called synchronously or asynchronously:

js
function doSomething(callback) {
  if (Math.random() > 0.5) {
    callback();
  } else {
    setTimeout(() => callback(), 1000);
  }
}

The above design is strongly discouraged because it leads to the so-called "state of Zalgo". In the context of designing asynchronous APIs, this means a callback is called synchronously in some cases but asynchronously in other cases, creating ambiguity for the caller. For further background, see the article Designing APIs for Asynchrony, where the term was first formally presented. This API design makes side effects hard to analyze:

js
let value = 1;
doSomething(() => {
  value = 2;
});
console.log(value); // 1 or 2?

On the other hand, promises are a form of inversion of control — the API implementor does not control when the callback gets called. Instead, the job of maintaining the callback queue and deciding when to call the callbacks is delegated to the promise implementation, and both the API user and API developer automatically get strong semantic guarantees, including:

  • Callbacks added with then() will never be invoked before the completion of the current run of the JavaScript event loop.
  • These callbacks will be invoked even if they were added after the success or failure of the asynchronous operation that the promise represents.
  • Multiple callbacks may be added by calling then() several times. They will be invoked one after another, in the order in which they were inserted.

To avoid surprises, functions passed to then() will never be called synchronously, even with an already-resolved promise:

js
Promise.resolve().then(() => console.log(2));
console.log(1);
// Logs: 1, 2

Instead of running immediately, the passed-in function is put on a microtask queue, which means it runs later (only after the function which created it exits, and when the JavaScript execution stack is empty), just before control is returned to the event loop; i.e., pretty soon:

js
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

wait(0).then(() => console.log(4));
Promise.resolve()
  .then(() => console.log(2))
  .then(() => console.log(3));
console.log(1); // 1, 2, 3, 4

Task queues vs. microtasks

Promise callbacks are handled as a microtask whereas setTimeout() callbacks are handled as task queues.

js
const promise = new Promise((resolve, reject) => {
  console.log("Promise callback");
  resolve();
}).then((result) => {
  console.log("Promise callback (.then)");
});

setTimeout(() => {
  console.log("event-loop cycle: Promise (fulfilled)", promise);
}, 0);

console.log("Promise (pending)", promise);

The code above will output:

Promise callback
Promise (pending) Promise {<pending>}
Promise callback (.then)
event-loop cycle: Promise (fulfilled) Promise {<fulfilled>}

For more details, refer to Tasks vs. microtasks.

When promises and tasks collide

If you run into situations in which you have promises and tasks (such as events or callbacks) which are firing in unpredictable orders, it's possible you may benefit from using a microtask to check status or balance out your promises when promises are created conditionally.

If you think microtasks may help solve this problem, see the microtask guide to learn more about how to use queueMicrotask() to enqueue a function as a microtask.

See also

5.5. Constraints #

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.

5.5. Constraints #

Data types are a way to limit the kind of data that can be stored in a table. For many applications, however, the constraint they provide is too coarse. For example, a column containing a product price should probably only accept positive values. But there is no standard data type that accepts only positive numbers. Another issue is that you might want to constrain column data with respect to other columns or rows. For example, in a table containing product information, there should be only one row for each product number.

To that end, SQL allows you to define constraints on columns and tables. Constraints give you as much control over the data in your tables as you wish. If a user attempts to store data in a column that would violate a constraint, an error is raised. This applies even if the value came from the default value definition.

5.5.1. Check Constraints #

A check constraint is the most generic constraint type. It allows you to specify that the value in a certain column must satisfy a Boolean (truth-value) expression. For instance, to require positive product prices, you could use:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0)
);

As you see, the constraint definition comes after the data type, just like default value definitions. Default values and constraints can be listed in any order. A check constraint consists of the key word CHECK followed by an expression in parentheses. The check constraint expression should involve the column thus constrained, otherwise the constraint would not make too much sense.

You can also give the constraint a separate name. This clarifies error messages and allows you to refer to the constraint when you need to change it. The syntax is:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CONSTRAINT positive_price CHECK (price > 0)
);

So, to specify a named constraint, use the key word CONSTRAINT followed by an identifier followed by the constraint definition. (If you don't specify a constraint name in this way, the system chooses a name for you.)

A check constraint can also refer to several columns. Say you store a regular price and a discounted price, and you want to ensure that the discounted price is lower than the regular price:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0),
    discounted_price numeric CHECK (discounted_price > 0),
    CHECK (price > discounted_price)
);

The first two constraints should look familiar. The third one uses a new syntax. It is not attached to a particular column, instead it appears as a separate item in the comma-separated column list. Column definitions and these constraint definitions can be listed in mixed order.

We say that the first two constraints are column constraints, whereas the third one is a table constraint because it is written separately from any one column definition. Column constraints can also be written as table constraints, while the reverse is not necessarily possible, since a column constraint is supposed to refer to only the column it is attached to. (PostgreSQL doesn't enforce that rule, but you should follow it if you want your table definitions to work with other database systems.) The above example could also be written as:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
    CHECK (price > 0),
    discounted_price numeric,
    CHECK (discounted_price > 0),
    CHECK (price > discounted_price)
);

or even:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0),
    discounted_price numeric,
    CHECK (discounted_price > 0 AND price > discounted_price)
);

It's a matter of taste.

Names can be assigned to table constraints in the same way as column constraints:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
    CHECK (price > 0),
    discounted_price numeric,
    CHECK (discounted_price > 0),
    CONSTRAINT valid_discount CHECK (price > discounted_price)
);

It should be noted that a check constraint is satisfied if the check expression evaluates to true or the null value. Since most expressions will evaluate to the null value if any operand is null, they will not prevent null values in the constrained columns. To ensure that a column does not contain null values, the not-null constraint described in the next section can be used.

Note

PostgreSQL does not support CHECK constraints that reference table data other than the new or updated row being checked. While a CHECK constraint that violates this rule may appear to work in simple tests, it cannot guarantee that the database will not reach a state in which the constraint condition is false (due to subsequent changes of the other row(s) involved). This would cause a database dump and restore to fail. The restore could fail even when the complete database state is consistent with the constraint, due to rows not being loaded in an order that will satisfy the constraint. If possible, use UNIQUE, EXCLUDE, or FOREIGN KEY constraints to express cross-row and cross-table restrictions.

If what you desire is a one-time check against other rows at row insertion, rather than a continuously-maintained consistency guarantee, a custom trigger can be used to implement that. (This approach avoids the dump/restore problem because pg_dump does not reinstall triggers until after restoring data, so that the check will not be enforced during a dump/restore.)

Note

PostgreSQL assumes that CHECK constraints' conditions are immutable, that is, they will always give the same result for the same input row. This assumption is what justifies examining CHECK constraints only when rows are inserted or updated, and not at other times. (The warning above about not referencing other table data is really a special case of this restriction.)

An example of a common way to break this assumption is to reference a user-defined function in a CHECK expression, and then change the behavior of that function. PostgreSQL does not disallow that, but it will not notice if there are rows in the table that now violate the CHECK constraint. That would cause a subsequent database dump and restore to fail. The recommended way to handle such a change is to drop the constraint (using ALTER TABLE), adjust the function definition, and re-add the constraint, thereby rechecking it against all table rows.

5.5.2. Not-Null Constraints #

A not-null constraint simply specifies that a column must not assume the null value. A syntax example:

CREATE TABLE products (
    product_no integer NOT NULL,
    name text NOT NULL,
    price numeric
);

An explicit constraint name can also be specified, for example:

CREATE TABLE products (
    product_no integer NOT NULL,
    name text CONSTRAINT products_name_not_null NOT NULL,
    price numeric
);

A not-null constraint is usually written as a column constraint. The syntax for writing it as a table constraint is

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
    NOT NULL product_no,
    NOT NULL name
);

But this syntax is not standard and mainly intended for use by pg_dump.

A not-null constraint is functionally equivalent to creating a check constraint CHECK (column_name IS NOT NULL), but in PostgreSQL creating an explicit not-null constraint is more efficient.

Of course, a column can have more than one constraint. Just write the constraints one after another:

CREATE TABLE products (
    product_no integer NOT NULL,
    name text NOT NULL,
    price numeric NOT NULL CHECK (price > 0)
);

The order doesn't matter. It does not necessarily determine in which order the constraints are checked.

However, a column can have at most one explicit not-null constraint.

The NOT NULL constraint has an inverse: the NULL constraint. This does not mean that the column must be null, which would surely be useless. Instead, this simply selects the default behavior that the column might be null. The NULL constraint is not present in the SQL standard and should not be used in portable applications. (It was only added to PostgreSQL to be compatible with some other database systems.) Some users, however, like it because it makes it easy to toggle the constraint in a script file. For example, you could start with:

CREATE TABLE products (
    product_no integer NULL,
    name text NULL,
    price numeric NULL
);

and then insert the NOT key word where desired.

Tip

In most database designs the majority of columns should be marked not null.

5.5.3. Unique Constraints #

Unique constraints ensure that the data contained in a column, or a group of columns, is unique among all the rows in the table. The syntax is:

CREATE TABLE products (
    product_no integer UNIQUE,
    name text,
    price numeric
);

when written as a column constraint, and:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
    UNIQUE (product_no)
);

when written as a table constraint.

To define a unique constraint for a group of columns, write it as a table constraint with the column names separated by commas:

CREATE TABLE example (
    a integer,
    b integer,
    c integer,
    UNIQUE (a, c)
);

This specifies that the combination of values in the indicated columns is unique across the whole table, though any one of the columns need not be (and ordinarily isn't) unique.

You can assign your own name for a unique constraint, in the usual way:

CREATE TABLE products (
    product_no integer CONSTRAINT must_be_different UNIQUE,
    name text,
    price numeric
);

Adding a unique constraint will automatically create a unique B-tree index on the column or group of columns listed in the constraint. A uniqueness restriction covering only some rows cannot be written as a unique constraint, but it is possible to enforce such a restriction by creating a unique partial index.

In general, a unique constraint is violated if there is more than one row in the table where the values of all of the columns included in the constraint are equal. By default, two null values are not considered equal in this comparison. That means even in the presence of a unique constraint it is possible to store duplicate rows that contain a null value in at least one of the constrained columns. This behavior can be changed by adding the clause NULLS NOT DISTINCT, like

CREATE TABLE products (
    product_no integer UNIQUE NULLS NOT DISTINCT,
    name text,
    price numeric
);

or

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
    UNIQUE NULLS NOT DISTINCT (product_no)
);

The default behavior can be specified explicitly using NULLS DISTINCT. The default null treatment in unique constraints is implementation-defined according to the SQL standard, and other implementations have a different behavior. So be careful when developing applications that are intended to be portable.

5.5.4. Primary Keys #

A primary key constraint indicates that a column, or group of columns, can be used as a unique identifier for rows in the table. This requires that the values be both unique and not null. So, the following two table definitions accept the same data:

CREATE TABLE products (
    product_no integer UNIQUE NOT NULL,
    name text,
    price numeric
);
CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);

Primary keys can span more than one column; the syntax is similar to unique constraints:

CREATE TABLE example (
    a integer,
    b integer,
    c integer,
    PRIMARY KEY (a, c)
);

Adding a primary key will automatically create a unique B-tree index on the column or group of columns listed in the primary key, and will force the column(s) to be marked NOT NULL.

A table can have at most one primary key. (There can be any number of unique constraints, which combined with not-null constraints are functionally almost the same thing, but only one can be identified as the primary key.) Relational database theory dictates that every table must have a primary key. This rule is not enforced by PostgreSQL, but it is usually best to follow it.

Primary keys are useful both for documentation purposes and for client applications. For example, a GUI application that allows modifying row values probably needs to know the primary key of a table to be able to identify rows uniquely. There are also various ways in which the database system makes use of a primary key if one has been declared; for example, the primary key defines the default target column(s) for foreign keys referencing its table.

5.5.5. Foreign Keys #

A foreign key constraint specifies that the values in a column (or a group of columns) must match the values appearing in some row of another table. We say this maintains the referential integrity between two related tables.

Say you have the product table that we have used several times already:

CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);

Let's also assume you have a table storing orders of those products. We want to ensure that the orders table only contains orders of products that actually exist. So we define a foreign key constraint in the orders table that references the products table:

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    product_no integer REFERENCES products (product_no),
    quantity integer
);

Now it is impossible to create orders with non-NULL product_no entries that do not appear in the products table.

We say that in this situation the orders table is the referencing table and the products table is the referenced table. Similarly, there are referencing and referenced columns.

You can also shorten the above command to:

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    product_no integer REFERENCES products,
    quantity integer
);

because in absence of a column list the primary key of the referenced table is used as the referenced column(s).

You can assign your own name for a foreign key constraint, in the usual way.

A foreign key can also constrain and reference a group of columns. As usual, it then needs to be written in table constraint form. Here is a contrived syntax example:

CREATE TABLE t1 (
  a integer PRIMARY KEY,
  b integer,
  c integer,
  FOREIGN KEY (b, c) REFERENCES other_table (c1, c2)
);

Of course, the number and type of the constrained columns need to match the number and type of the referenced columns.

Sometimes it is useful for the “other table” of a foreign key constraint to be the same table; this is called a self-referential foreign key. For example, if you want rows of a table to represent nodes of a tree structure, you could write

CREATE TABLE tree (
    node_id integer PRIMARY KEY,
    parent_id integer REFERENCES tree,
    name text,
    ...
);

A top-level node would have NULL parent_id, while non-NULL parent_id entries would be constrained to reference valid rows of the table.

A table can have more than one foreign key constraint. This is used to implement many-to-many relationships between tables. Say you have tables about products and orders, but now you want to allow one order to contain possibly many products (which the structure above did not allow). You could use this table structure:

CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    shipping_address text,
    ...
);

CREATE TABLE order_items (
    product_no integer REFERENCES products,
    order_id integer REFERENCES orders,
    quantity integer,
    PRIMARY KEY (product_no, order_id)
);

Notice that the primary key overlaps with the foreign keys in the last table.

We know that the foreign keys disallow creation of orders that do not relate to any products. But what if a product is removed after an order is created that references it? SQL allows you to handle that as well. Intuitively, we have a few options:

  • Disallow deleting a referenced product

  • Delete the orders as well

  • Something else?

To illustrate this, let's implement the following policy on the many-to-many relationship example above: when someone wants to remove a product that is still referenced by an order (via order_items), we disallow it. If someone removes an order, the order items are removed as well:

CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    shipping_address text,
    ...
);

CREATE TABLE order_items (
    product_no integer REFERENCES products ON DELETE RESTRICT,
    order_id integer REFERENCES orders ON DELETE CASCADE,
    quantity integer,
    PRIMARY KEY (product_no, order_id)
);

The default ON DELETE action is ON DELETE NO ACTION; this does not need to be specified. This means that the deletion in the referenced table is allowed to proceed. But the foreign-key constraint is still required to be satisfied, so this operation will usually result in an error. But checking of foreign-key constraints can also be deferred to later in the transaction (not covered in this chapter). In that case, the NO ACTION setting would allow other commands to “fix” the situation before the constraint is checked, for example by inserting another suitable row into the referenced table or by deleting the now-dangling rows from the referencing table.

RESTRICT is a stricter setting than NO ACTION. It prevents deletion of a referenced row. RESTRICT does not allow the check to be deferred until later in the transaction.

CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well.

There are two other options: SET NULL and SET DEFAULT. These cause the referencing column(s) in the referencing row(s) to be set to nulls or their default values, respectively, when the referenced row is deleted. Note that these do not excuse you from observing any constraints. For example, if an action specifies SET DEFAULT but the default value would not satisfy the foreign key constraint, the operation will fail.

The appropriate choice of ON DELETE action depends on what kinds of objects the related tables represent. When the referencing table represents something that is a component of what is represented by the referenced table and cannot exist independently, then CASCADE could be appropriate. If the two tables represent independent objects, then RESTRICT or NO ACTION is more appropriate; an application that actually wants to delete both objects would then have to be explicit about this and run two delete commands. In the above example, order items are part of an order, and it is convenient if they are deleted automatically if an order is deleted. But products and orders are different things, and so making a deletion of a product automatically cause the deletion of some order items could be considered problematic. The actions SET NULL or SET DEFAULT can be appropriate if a foreign-key relationship represents optional information. For example, if the products table contained a reference to a product manager, and the product manager entry gets deleted, then setting the product's product manager to null or a default might be useful.

The actions SET NULL and SET DEFAULT can take a column list to specify which columns to set. Normally, all columns of the foreign-key constraint are set; setting only a subset is useful in some special cases. Consider the following example:

CREATE TABLE tenants (
    tenant_id integer PRIMARY KEY
);

CREATE TABLE users (
    tenant_id integer REFERENCES tenants ON DELETE CASCADE,
    user_id integer NOT NULL,
    PRIMARY KEY (tenant_id, user_id)
);

CREATE TABLE posts (
    tenant_id integer REFERENCES tenants ON DELETE CASCADE,
    post_id integer NOT NULL,
    author_id integer,
    PRIMARY KEY (tenant_id, post_id),
    FOREIGN KEY (tenant_id, author_id) REFERENCES users ON DELETE SET NULL (author_id)
);

Without the specification of the column, the foreign key would also set the column tenant_id to null, but that column is still required as part of the primary key.

Analogous to ON DELETE there is also ON UPDATE which is invoked when a referenced column is changed (updated). The possible actions are the same, except that column lists cannot be specified for SET NULL and SET DEFAULT. In this case, CASCADE means that the updated values of the referenced column(s) should be copied into the referencing row(s). There is also a noticeable difference between ON UPDATE NO ACTION (the default) and ON UPDATE RESTRICT. The former will allow the update to proceed and the foreign-key constraint will be checked against the state after the update. The latter will prevent the update to run even if the state after the update would still satisfy the constraint. This prevents updating a referenced row to a value that is distinct but compares as equal (for example, a character string with a different case variant, if a character string type with a case-insensitive collation is used).

Normally, a referencing row need not satisfy the foreign key constraint if any of its referencing columns are null. If MATCH FULL is added to the foreign key declaration, a referencing row escapes satisfying the constraint only if all its referencing columns are null (so a mix of null and non-null values is guaranteed to fail a MATCH FULL constraint). If you don't want referencing rows to be able to avoid satisfying the foreign key constraint, declare the referencing column(s) as NOT NULL.

A foreign key must reference columns that either are a primary key or form a unique constraint, or are columns from a non-partial unique index. This means that the referenced columns always have an index to allow efficient lookups on whether a referencing row has a match. Since a DELETE of a row from the referenced table or an UPDATE of a referenced column will require a scan of the referencing table for rows matching the old value, it is often a good idea to index the referencing columns too. Because this is not always needed, and there are many choices available on how to index, the declaration of a foreign key constraint does not automatically create an index on the referencing columns.

More information about updating and deleting data is in Chapter 6. Also see the description of foreign key constraint syntax in the reference documentation for CREATE TABLE.

5.5.6. Exclusion Constraints #

Exclusion constraints ensure that if any two rows are compared on the specified columns or expressions using the specified operators, at least one of these operator comparisons will return false or null. The syntax is:

CREATE TABLE circles (
    c circle,
    EXCLUDE USING gist (c WITH &&)
);

See also CREATE TABLE ... CONSTRAINT ... EXCLUDE for details.

Adding an exclusion constraint will automatically create an index of the type specified in the constraint declaration.

2.5. Automatic Differentiation 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.

2.5. Automatic Differentiation
Open the notebook in SageMaker Studio Lab

Recall from Section 2.4 that calculating derivatives is the crucial step in all the optimization algorithms that we will use to train deep networks. While the calculations are straightforward, working them out by hand can be tedious and error-prone, and these issues only grow as our models become more complex.

Fortunately all modern deep learning frameworks take this work off our plates by offering automatic differentiation (often shortened to autograd). As we pass data through each successive function, the framework builds a computational graph that tracks how each value depends on others. To calculate derivatives, automatic differentiation works backwards through this graph applying the chain rule. The computational algorithm for applying the chain rule in this fashion is called backpropagation.

While autograd libraries have become a hot concern over the past decade, they have a long history. In fact the earliest references to autograd date back over half of a century (Wengert, 1964). The core ideas behind modern backpropagation date to a PhD thesis from 1980 (Speelpenning, 1980) and were further developed in the late 1980s (Griewank, 1989). While backpropagation has become the default method for computing gradients, it is not the only option. For instance, the Julia programming language employs forward propagation (Revels et al., 2016). Before exploring methods, let’s first master the autograd package.

import torch

2.5.1. A Simple Function

Let’s assume that we are interested in differentiating the function \(y = 2\mathbf{x}^{\top}\mathbf{x}\) with respect to the column vector \(\mathbf{x}\). To start, we assign x an initial value.

x = torch.arange(4.0)
x
tensor([0., 1., 2., 3.])

Before we calculate the gradient of \(y\) with respect to \(\mathbf{x}\), we need a place to store it. In general, we avoid allocating new memory every time we take a derivative because deep learning requires successively computing derivatives with respect to the same parameters a great many times, and we might risk running out of memory. Note that the gradient of a scalar-valued function with respect to a vector \(\mathbf{x}\) is vector-valued with the same shape as \(\mathbf{x}\).

# Can also create x = torch.arange(4.0, requires_grad=True)
x.requires_grad_(True)
x.grad  # The gradient is None by default

We now calculate our function of x and assign the result to y.

y = 2 * torch.dot(x, x)
y
tensor(28., grad_fn=<MulBackward0>)

We can now take the gradient of y with respect to x by calling its backward method. Next, we can access the gradient via x’s grad attribute.

y.backward()
x.grad
tensor([ 0.,  4.,  8., 12.])

We already know that the gradient of the function \(y = 2\mathbf{x}^{\top}\mathbf{x}\) with respect to \(\mathbf{x}\) should be \(4\mathbf{x}\). We can now verify that the automatic gradient computation and the expected result are identical.

x.grad == 4 * x
tensor([True, True, True, True])

Now let’s calculate another function of x and take its gradient. Note that PyTorch does not automatically reset the gradient buffer when we record a new gradient. Instead, the new gradient is added to the already-stored gradient. This behavior comes in handy when we want to optimize the sum of multiple objective functions. To reset the gradient buffer, we can call x.grad.zero_() as follows:

x.grad.zero_()  # Reset the gradient
y = x.sum()
y.backward()
x.grad
tensor([1., 1., 1., 1.])

2.5.2. Backward for Non-Scalar Variables

When y is a vector, the most natural representation of the derivative of y with respect to a vector x is a matrix called the Jacobian that contains the partial derivatives of each component of y with respect to each component of x. Likewise, for higher-order y and x, the result of differentiation could be an even higher-order tensor.

While Jacobians do show up in some advanced machine learning techniques, more commonly we want to sum up the gradients of each component of y with respect to the full vector x, yielding a vector of the same shape as x. For example, we often have a vector representing the value of our loss function calculated separately for each example among a batch of training examples. Here, we just want to sum up the gradients computed individually for each example.

Because deep learning frameworks vary in how they interpret gradients of non-scalar tensors, PyTorch takes some steps to avoid confusion. Invoking backward on a non-scalar elicits an error unless we tell PyTorch how to reduce the object to a scalar. More formally, we need to provide some vector \(\mathbf{v}\) such that backward will compute \(\mathbf{v}^\top \partial_{\mathbf{x}} \mathbf{y}\) rather than \(\partial_{\mathbf{x}} \mathbf{y}\). This next part may be confusing, but for reasons that will become clear later, this argument (representing \(\mathbf{v}\)) is named gradient. For a more detailed description, see Yang Zhang’s Medium post.

x.grad.zero_()
y = x * x
y.backward(gradient=torch.ones(len(y)))  # Faster: y.sum().backward()
x.grad
tensor([0., 2., 4., 6.])

2.5.3. Detaching Computation

Sometimes, we wish to move some calculations outside of the recorded computational graph. For example, say that we use the input to create some auxiliary intermediate terms for which we do not want to compute a gradient. In this case, we need to detach the respective computational graph from the final result. The following toy example makes this clearer: suppose we have z = x * y and y = x * x but we want to focus on the direct influence of x on z rather than the influence conveyed via y. In this case, we can create a new variable u that takes the same value as y but whose provenance (how it was created) has been wiped out. Thus u has no ancestors in the graph and gradients do not flow through u to x. For example, taking the gradient of z = x * u will yield the result u, (not 3 * x * x as you might have expected since z = x * x * x).

x.grad.zero_()
y = x * x
u = y.detach()
z = u * x

z.sum().backward()
x.grad == u
tensor([True, True, True, True])

Note that while this procedure detaches y’s ancestors from the graph leading to z, the computational graph leading to y persists and thus we can calculate the gradient of y with respect to x.

x.grad.zero_()
y.sum().backward()
x.grad == 2 * x
tensor([True, True, True, True])

2.5.4. Gradients and Python Control Flow

So far we reviewed cases where the path from input to output was well defined via a function such as z = x * x * x. Programming offers us a lot more freedom in how we compute results. For instance, we can make them depend on auxiliary variables or condition choices on intermediate results. One benefit of using automatic differentiation is that even if building the computational graph of a function required passing through a maze of Python control flow (e.g., conditionals, loops, and arbitrary function calls), we can still calculate the gradient of the resulting variable. To illustrate this, consider the following code snippet where the number of iterations of the while loop and the evaluation of the if statement both depend on the value of the input a.

def f(a):
    b = a * 2
    while b.norm() < 1000:
        b = b * 2
    if b.sum() > 0:
        c = b
    else:
        c = 100 * b
    return c

Below, we call this function, passing in a random value, as input. Since the input is a random variable, we do not know what form the computational graph will take. However, whenever we execute f(a) on a specific input, we realize a specific computational graph and can subsequently run backward.

a = torch.randn(size=(), requires_grad=True)
d = f(a)
d.backward()

Even though our function f is, for demonstration purposes, a bit contrived, its dependence on the input is quite simple: it is a linear function of a with piecewise defined scale. As such, f(a) / a is a vector of constant entries and, moreover, f(a) / a needs to match the gradient of f(a) with respect to a.

a.grad == d / a
tensor(True)

Dynamic control flow is very common in deep learning. For instance, when processing text, the computational graph depends on the length of the input. In these cases, automatic differentiation becomes vital for statistical modeling since it is impossible to compute the gradient a priori.

2.5.5. Discussion

You have now gotten a taste of the power of automatic differentiation. The development of libraries for calculating derivatives both automatically and efficiently has been a massive productivity booster for deep learning practitioners, liberating them so they can focus on less menial. Moreover, autograd lets us design massive models for which pen and paper gradient computations would be prohibitively time consuming. Interestingly, while we use autograd to optimize models (in a statistical sense) the optimization of autograd libraries themselves (in a computational sense) is a rich subject of vital interest to framework designers. Here, tools from compilers and graph manipulation are leveraged to compute results in the most expedient and memory-efficient manner.

For now, try to remember these basics: (i) attach gradients to those variables with respect to which we desire derivatives; (ii) record the computation of the target value; (iii) execute the backpropagation function; and (iv) access the resulting gradient.

2.5.6. Exercises

  1. Why is the second derivative much more expensive to compute than the first derivative?

  2. After running the function for backpropagation, immediately run it again and see what happens. Investigate.

  3. In the control flow example where we calculate the derivative of d with respect to a, what would happen if we changed the variable a to a random vector or a matrix? At this point, the result of the calculation f(a) is no longer a scalar. What happens to the result? How do we analyze this?

  4. Let \(f(x) = \sin(x)\). Plot the graph of \(f\) and of its derivative \(f'\). Do not exploit the fact that \(f'(x) = \cos(x)\) but rather use automatic differentiation to get the result.

  5. Let \(f(x) = ((\log x^2) \cdot \sin x) + x^{-1}\). Write out a dependency graph tracing results from \(x\) to \(f(x)\).

  6. Use the chain rule to compute the derivative \(\frac{df}{dx}\) of the aforementioned function, placing each term on the dependency graph that you constructed previously.

  7. Given the graph and the intermediate derivative results, you have a number of options when computing the gradient. Evaluate the result once starting from \(x\) to \(f\) and once from \(f\) tracing back to \(x\). The path from \(x\) to \(f\) is commonly known as forward differentiation, whereas the path from \(f\) to \(x\) is known as backward differentiation.

  8. When might you want to use forward, and when backward, differentiation? Hint: consider the amount of intermediate data needed, the ability to parallelize steps, and the size of matrices and vectors involved.

4.1. Softmax Regression 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.

4.1. Softmax Regression
Open the notebook in SageMaker Studio Lab

In Section 3.1, we introduced linear regression, working through implementations from scratch in Section 3.4 and again using high-level APIs of a deep learning framework in Section 3.5 to do the heavy lifting.

Regression is the hammer we reach for when we want to answer how much? or how many? questions. If you want to predict the number of dollars (price) at which a house will be sold, or the number of wins a baseball team might have, or the number of days that a patient will remain hospitalized before being discharged, then you are probably looking for a regression model. However, even within regression models, there are important distinctions. For instance, the price of a house will never be negative and changes might often be relative to its baseline price. As such, it might be more effective to regress on the logarithm of the price. Likewise, the number of days a patient spends in hospital is a discrete nonnegative random variable. As such, least mean squares might not be an ideal approach either. This sort of time-to-event modeling comes with a host of other complications that are dealt with in a specialized subfield called survival modeling.

The point here is not to overwhelm you but just to let you know that there is a lot more to estimation than simply minimizing squared errors. And more broadly, there is a lot more to supervised learning than regression. In this section, we focus on classification problems where we put aside how much? questions and instead focus on which category? questions.

  • Does this email belong in the spam folder or the inbox?

  • Is this customer more likely to sign up or not to sign up for a subscription service?

  • Does this image depict a donkey, a dog, a cat, or a rooster?

  • Which movie is Aston most likely to watch next?

  • Which section of the book are you going to read next?

Colloquially, machine learning practitioners overload the word classification to describe two subtly different problems: (i) those where we are interested only in hard assignments of examples to categories (classes); and (ii) those where we wish to make soft assignments, i.e., to assess the probability that each category applies. The distinction tends to get blurred, in part, because often, even when we only care about hard assignments, we still use models that make soft assignments.

Even more, there are cases where more than one label might be true. For instance, a news article might simultaneously cover the topics of entertainment, business, and space flight, but not the topics of medicine or sports. Thus, categorizing it into one of the above categories on their own would not be very useful. This problem is commonly known as multi-label classification. See Tsoumakas and Katakis (2007) for an overview and Huang et al. (2015) for an effective algorithm when tagging images.

4.1.1. Classification

To get our feet wet, let’s start with a simple image classification problem. Here, each input consists of a \(2\times2\) grayscale image. We can represent each pixel value with a single scalar, giving us four features \(x_1, x_2, x_3, x_4\). Further, let’s assume that each image belongs to one among the categories “cat”, “chicken”, and “dog”.

Next, we have to choose how to represent the labels. We have two obvious choices. Perhaps the most natural impulse would be to choose \(y \in \{1, 2, 3\}\), where the integers represent \(\{\textrm{dog}, \textrm{cat}, \textrm{chicken}\}\) respectively. This is a great way of storing such information on a computer. If the categories had some natural ordering among them, say if we were trying to predict \(\{\textrm{baby}, \textrm{toddler}, \textrm{adolescent}, \textrm{young adult}, \textrm{adult}, \textrm{geriatric}\}\), then it might even make sense to cast this as an ordinal regression problem and keep the labels in this format. See Moon et al. (2010) for an overview of different types of ranking loss functions and Beutel et al. (2014) for a Bayesian approach that addresses responses with more than one mode.

In general, classification problems do not come with natural orderings among the classes. Fortunately, statisticians long ago invented a simple way to represent categorical data: the one-hot encoding. A one-hot encoding is a vector with as many components as we have categories. The component corresponding to a particular instance’s category is set to 1 and all other components are set to 0. In our case, a label \(y\) would be a three-dimensional vector, with \((1, 0, 0)\) corresponding to “cat”, \((0, 1, 0)\) to “chicken”, and \((0, 0, 1)\) to “dog”:

(4.1.1)\[y \in \{(1, 0, 0), (0, 1, 0), (0, 0, 1)\}.\]

4.1.1.1. Linear Model

In order to estimate the conditional probabilities associated with all the possible classes, we need a model with multiple outputs, one per class. To address classification with linear models, we will need as many affine functions as we have outputs. Strictly speaking, we only need one fewer, since the final category has to be the difference between \(1\) and the sum of the other categories, but for reasons of symmetry we use a slightly redundant parametrization. Each output corresponds to its own affine function. In our case, since we have 4 features and 3 possible output categories, we need 12 scalars to represent the weights (\(w\) with subscripts), and 3 scalars to represent the biases (\(b\) with subscripts). This yields:

(4.1.2)\[\begin{split}\begin{aligned} o_1 &= x_1 w_{11} + x_2 w_{12} + x_3 w_{13} + x_4 w_{14} + b_1,\\ o_2 &= x_1 w_{21} + x_2 w_{22} + x_3 w_{23} + x_4 w_{24} + b_2,\\ o_3 &= x_1 w_{31} + x_2 w_{32} + x_3 w_{33} + x_4 w_{34} + b_3. \end{aligned}\end{split}\]

The corresponding neural network diagram is shown in Fig. 4.1.1. Just as in linear regression, we use a single-layer neural network. And since the calculation of each output, \(o_1, o_2\), and \(o_3\), depends on every input, \(x_1\), \(x_2\), \(x_3\), and \(x_4\), the output layer can also be described as a fully connected layer.

../_images/softmaxreg.svg

Fig. 4.1.1 Softmax regression is a single-layer neural network.

For a more concise notation we use vectors and matrices: \(\mathbf{o} = \mathbf{W} \mathbf{x} + \mathbf{b}\) is much better suited for mathematics and code. Note that we have gathered all of our weights into a \(3 \times 4\) matrix and all biases \(\mathbf{b} \in \mathbb{R}^3\) in a vector.

4.1.1.2. The Softmax

Assuming a suitable loss function, we could try, directly, to minimize the difference between \(\mathbf{o}\) and the labels \(\mathbf{y}\). While it turns out that treating classification as a vector-valued regression problem works surprisingly well, it is nonetheless unsatisfactory in the following ways:

  • There is no guarantee that the outputs \(o_i\) sum up to \(1\) in the way we expect probabilities to behave.

  • There is no guarantee that the outputs \(o_i\) are even nonnegative, even if their outputs sum up to \(1\), or that they do not exceed \(1\).

Both aspects render the estimation problem difficult to solve and the solution very brittle to outliers. For instance, if we assume that there is a positive linear dependency between the number of bedrooms and the likelihood that someone will buy a house, the probability might exceed \(1\) when it comes to buying a mansion! As such, we need a mechanism to “squish” the outputs.

There are many ways we might accomplish this goal. For instance, we could assume that the outputs \(\mathbf{o}\) are corrupted versions of \(\mathbf{y}\), where the corruption occurs by means of adding noise \(\boldsymbol{\epsilon}\) drawn from a normal distribution. In other words, \(\mathbf{y} = \mathbf{o} + \boldsymbol{\epsilon}\), where \(\epsilon_i \sim \mathcal{N}(0, \sigma^2)\). This is the so-called probit model, first introduced by Fechner (1860). While appealing, it does not work quite as well nor lead to a particularly nice optimization problem, when compared to the softmax.

Another way to accomplish this goal (and to ensure nonnegativity) is to use an exponential function \(P(y = i) \propto \exp o_i\). This does indeed satisfy the requirement that the conditional class probability increases with increasing \(o_i\), it is monotonic, and all probabilities are nonnegative. We can then transform these values so that they add up to \(1\) by dividing each by their sum. This process is called normalization. Putting these two pieces together gives us the softmax function:

(4.1.3)\[\hat{\mathbf{y}} = \mathrm{softmax}(\mathbf{o}) \quad \textrm{where}\quad \hat{y}_i = \frac{\exp(o_i)}{\sum_j \exp(o_j)}.\]

Note that the largest coordinate of \(\mathbf{o}\) corresponds to the most likely class according to \(\hat{\mathbf{y}}\). Moreover, because the softmax operation preserves the ordering among its arguments, we do not need to compute the softmax to determine which class has been assigned the highest probability. Thus,

(4.1.4)\[\operatorname*{argmax}_j \hat y_j = \operatorname*{argmax}_j o_j.\]

The idea of a softmax dates back to Gibbs (1902), who adapted ideas from physics. Dating even further back, Boltzmann, the father of modern statistical physics, used this trick to model a distribution over energy states in gas molecules. In particular, he discovered that the prevalence of a state of energy in a thermodynamic ensemble, such as the molecules in a gas, is proportional to \(\exp(-E/kT)\). Here, \(E\) is the energy of a state, \(T\) is the temperature, and \(k\) is the Boltzmann constant. When statisticians talk about increasing or decreasing the “temperature” of a statistical system, they refer to changing \(T\) in order to favor lower or higher energy states. Following Gibbs’ idea, energy equates to error. Energy-based models (Ranzato et al., 2007) use this point of view when describing problems in deep learning.

4.1.1.3. Vectorization

To improve computational efficiency, we vectorize calculations in minibatches of data. Assume that we are given a minibatch \(\mathbf{X} \in \mathbb{R}^{n \times d}\) of \(n\) examples with dimensionality (number of inputs) \(d\). Moreover, assume that we have \(q\) categories in the output. Then the weights satisfy \(\mathbf{W} \in \mathbb{R}^{d \times q}\) and the bias satisfies \(\mathbf{b} \in \mathbb{R}^{1\times q}\).

(4.1.5)\[\begin{split}\begin{aligned} \mathbf{O} &= \mathbf{X} \mathbf{W} + \mathbf{b}, \\ \hat{\mathbf{Y}} & = \mathrm{softmax}(\mathbf{O}). \end{aligned}\end{split}\]

This accelerates the dominant operation into a matrix–matrix product \(\mathbf{X} \mathbf{W}\). Moreover, since each row in \(\mathbf{X}\) represents a data example, the softmax operation itself can be computed rowwise: for each row of \(\mathbf{O}\), exponentiate all entries and then normalize them by the sum. Note, though, that care must be taken to avoid exponentiating and taking logarithms of large numbers, since this can cause numerical overflow or underflow. Deep learning frameworks take care of this automatically.

4.1.2. Loss Function

Now that we have a mapping from features \(\mathbf{x}\) to probabilities \(\mathbf{\hat{y}}\), we need a way to optimize the accuracy of this mapping. We will rely on maximum likelihood estimation, the very same method that we encountered when providing a probabilistic justification for the mean squared error loss in Section 3.1.3.

4.1.2.1. Log-Likelihood

The softmax function gives us a vector \(\hat{\mathbf{y}}\), which we can interpret as the (estimated) conditional probabilities of each class, given any input \(\mathbf{x}\), such as \(\hat{y}_1\) = \(P(y=\textrm{cat} \mid \mathbf{x})\). In the following we assume that for a dataset with features \(\mathbf{X}\) the labels \(\mathbf{Y}\) are represented using a one-hot encoding label vector. We can compare the estimates with reality by checking how probable the actual classes are according to our model, given the features:

(4.1.6)\[P(\mathbf{Y} \mid \mathbf{X}) = \prod_{i=1}^n P(\mathbf{y}^{(i)} \mid \mathbf{x}^{(i)}).\]

We are allowed to use the factorization since we assume that each label is drawn independently from its respective distribution \(P(\mathbf{y}\mid\mathbf{x}^{(i)})\). Since maximizing the product of terms is awkward, we take the negative logarithm to obtain the equivalent problem of minimizing the negative log-likelihood:

(4.1.7)\[-\log P(\mathbf{Y} \mid \mathbf{X}) = \sum_{i=1}^n -\log P(\mathbf{y}^{(i)} \mid \mathbf{x}^{(i)}) = \sum_{i=1}^n l(\mathbf{y}^{(i)}, \hat{\mathbf{y}}^{(i)}),\]

where for any pair of label \(\mathbf{y}\) and model prediction \(\hat{\mathbf{y}}\) over \(q\) classes, the loss function \(l\) is

(4.1.8)\[l(\mathbf{y}, \hat{\mathbf{y}}) = - \sum_{j=1}^q y_j \log \hat{y}_j.\]

For reasons explained later on, the loss function in (4.1.8) is commonly called the cross-entropy loss. Since \(\mathbf{y}\) is a one-hot vector of length \(q\), the sum over all its coordinates \(j\) vanishes for all but one term. Note that the loss \(l(\mathbf{y}, \hat{\mathbf{y}})\) is bounded from below by \(0\) whenever \(\hat{\mathbf{y}}\) is a probability vector: no single entry is larger than \(1\), hence their negative logarithm cannot be lower than \(0\); \(l(\mathbf{y}, \hat{\mathbf{y}}) = 0\) only if we predict the actual label with certainty. This can never happen for any finite setting of the weights because taking a softmax output towards \(1\) requires taking the corresponding input \(o_i\) to infinity (or all other outputs \(o_j\) for \(j \neq i\) to negative infinity). Even if our model could assign an output probability of \(0\), any error made when assigning such high confidence would incur infinite loss (\(-\log 0 = \infty\)).

4.1.2.2. Softmax and Cross-Entropy Loss

Since the softmax function and the corresponding cross-entropy loss are so common, it is worth understanding a bit better how they are computed. Plugging (4.1.3) into the definition of the loss in (4.1.8) and using the definition of the softmax we obtain

(4.1.9)\[\begin{split}\begin{aligned} l(\mathbf{y}, \hat{\mathbf{y}}) &= - \sum_{j=1}^q y_j \log \frac{\exp(o_j)}{\sum_{k=1}^q \exp(o_k)} \\ &= \sum_{j=1}^q y_j \log \sum_{k=1}^q \exp(o_k) - \sum_{j=1}^q y_j o_j \\ &= \log \sum_{k=1}^q \exp(o_k) - \sum_{j=1}^q y_j o_j. \end{aligned}\end{split}\]

To understand a bit better what is going on, consider the derivative with respect to any logit \(o_j\). We get

(4.1.10)\[\partial_{o_j} l(\mathbf{y}, \hat{\mathbf{y}}) = \frac{\exp(o_j)}{\sum_{k=1}^q \exp(o_k)} - y_j = \mathrm{softmax}(\mathbf{o})_j - y_j.\]

In other words, the derivative is the difference between the probability assigned by our model, as expressed by the softmax operation, and what actually happened, as expressed by elements in the one-hot label vector. In this sense, it is very similar to what we saw in regression, where the gradient was the difference between the observation \(y\) and estimate \(\hat{y}\). This is not a coincidence. In any exponential family model, the gradients of the log-likelihood are given by precisely this term. This fact makes computing gradients easy in practice.

Now consider the case where we observe not just a single outcome but an entire distribution over outcomes. We can use the same representation as before for the label \(\mathbf{y}\). The only difference is that rather than a vector containing only binary entries, say \((0, 0, 1)\), we now have a generic probability vector, say \((0.1, 0.2, 0.7)\). The math that we used previously to define the loss \(l\) in (4.1.8) still works well, just that the interpretation is slightly more general. It is the expected value of the loss for a distribution over labels. This loss is called the cross-entropy loss and it is one of the most commonly used losses for classification problems. We can demystify the name by introducing just the basics of information theory. In a nutshell, it measures the number of bits needed to encode what we see, \(\mathbf{y}\), relative to what we predict that should happen, \(\hat{\mathbf{y}}\). We provide a very basic explanation in the following. For further details on information theory see Cover and Thomas (1999) or MacKay (2003).

4.1.3. Information Theory Basics

Many deep learning papers use intuition and terms from information theory. To make sense of them, we need some common language. This is a survival guide. Information theory deals with the problem of encoding, decoding, transmitting, and manipulating information (also known as data).

4.1.3.1. Entropy

The central idea in information theory is to quantify the amount of information contained in data. This places a limit on our ability to compress data. For a distribution \(P\) its entropy, \(H[P]\), is defined as:

(4.1.11)\[H[P] = \sum_j - P(j) \log P(j).\]

One of the fundamental theorems of information theory states that in order to encode data drawn randomly from the distribution \(P\), we need at least \(H[P]\) “nats” to encode it (Shannon, 1948). If you wonder what a “nat” is, it is the equivalent of bit but when using a code with base \(e\) rather than one with base 2. Thus, one nat is \(\frac{1}{\log(2)} \approx 1.44\) bit.

4.1.3.2. Surprisal

You might be wondering what compression has to do with prediction. Imagine that we have a stream of data that we want to compress. If it is always easy for us to predict the next token, then this data is easy to compress. Take the extreme example where every token in the stream always takes the same value. That is a very boring data stream! And not only it is boring, but it is also easy to predict. Because the tokens are always the same, we do not have to transmit any information to communicate the contents of the stream. Easy to predict, easy to compress.

However if we cannot perfectly predict every event, then we might sometimes be surprised. Our surprise is greater when an event is assigned lower probability. Claude Shannon settled on \(\log \frac{1}{P(j)} = -\log P(j)\) to quantify one’s surprisal at observing an event \(j\) having assigned it a (subjective) probability \(P(j)\). The entropy defined in (4.1.11) is then the expected surprisal when one assigned the correct probabilities that truly match the data-generating process.

4.1.3.3. Cross-Entropy Revisited

So if entropy is the level of surprise experienced by someone who knows the true probability, then you might be wondering, what is cross-entropy? The cross-entropy from \(P\) to \(Q\), denoted \(H(P, Q)\), is the expected surprisal of an observer with subjective probabilities \(Q\) upon seeing data that was actually generated according to probabilities \(P\). This is given by \(H(P, Q) \stackrel{\textrm{def}}{=} \sum_j - P(j) \log Q(j)\). The lowest possible cross-entropy is achieved when \(P=Q\). In this case, the cross-entropy from \(P\) to \(Q\) is \(H(P, P)= H(P)\).

In short, we can think of the cross-entropy classification objective in two ways: (i) as maximizing the likelihood of the observed data; and (ii) as minimizing our surprisal (and thus the number of bits) required to communicate the labels.

4.1.4. Summary and Discussion

In this section, we encountered the first nontrivial loss function, allowing us to optimize over discrete output spaces. Key in its design was that we took a probabilistic approach, treating discrete categories as instances of draws from a probability distribution. As a side effect, we encountered the softmax, a convenient activation function that transforms outputs of an ordinary neural network layer into valid discrete probability distributions. We saw that the derivative of the cross-entropy loss when combined with softmax behaves very similarly to the derivative of squared error; namely by taking the difference between the expected behavior and its prediction. And, while we were only able to scratch the very surface of it, we encountered exciting connections to statistical physics and information theory.

While this is enough to get you on your way, and hopefully enough to whet your appetite, we hardly dived deep here. Among other things, we skipped over computational considerations. Specifically, for any fully connected layer with \(d\) inputs and \(q\) outputs, the parametrization and computational cost is \(\mathcal{O}(dq)\), which can be prohibitively high in practice. Fortunately, this cost of transforming \(d\) inputs into \(q\) outputs can be reduced through approximation and compression. For instance Deep Fried Convnets (Yang et al., 2015) uses a combination of permutations, Fourier transforms, and scaling to reduce the cost from quadratic to log-linear. Similar techniques work for more advanced structural matrix approximations (Sindhwani et al., 2015). Lastly, we can use quaternion-like decompositions to reduce the cost to \(\mathcal{O}(\frac{dq}{n})\), again if we are willing to trade off a small amount of accuracy for computational and storage cost (Zhang et al., 2021) based on a compression factor \(n\). This is an active area of research. What makes it challenging is that we do not necessarily strive for the most compact representation or the smallest number of floating point operations but rather for the solution that can be executed most efficiently on modern GPUs.

4.1.5. Exercises

  1. We can explore the connection between exponential families and softmax in some more depth.

    1. Compute the second derivative of the cross-entropy loss \(l(\mathbf{y},\hat{\mathbf{y}})\) for softmax.

    2. Compute the variance of the distribution given by \(\mathrm{softmax}(\mathbf{o})\) and show that it matches the second derivative computed above.

  2. Assume that we have three classes which occur with equal probability, i.e., the probability vector is \((\frac{1}{3}, \frac{1}{3}, \frac{1}{3})\).

    1. What is the problem if we try to design a binary code for it?

    2. Can you design a better code? Hint: what happens if we try to encode two independent observations? What if we encode \(n\) observations jointly?

  3. When encoding signals transmitted over a physical wire, engineers do not always use binary codes. For instance, PAM-3 uses three signal levels \(\{-1, 0, 1\}\) as opposed to two levels \(\{0, 1\}\). How many ternary units do you need to transmit an integer in the range \(\{0, \ldots, 7\}\)? Why might this be a better idea in terms of electronics?

  4. The Bradley–Terry model uses a logistic model to capture preferences. For a user to choose between apples and oranges one assumes scores \(o_{\textrm{apple}}\) and \(o_{\textrm{orange}}\). Our requirements are that larger scores should lead to a higher likelihood in choosing the associated item and that the item with the largest score is the most likely one to be chosen (Bradley and Terry, 1952).

    1. Prove that softmax satisfies this requirement.

    2. What happens if you want to allow for a default option of choosing neither apples nor oranges? Hint: now the user has three choices.

  5. Softmax gets its name from the following mapping: \(\textrm{RealSoftMax}(a, b) = \log (\exp(a) + \exp(b))\).

    1. Prove that \(\textrm{RealSoftMax}(a, b) > \mathrm{max}(a, b)\).

    2. How small can you make the difference between both functions? Hint: without loss of generality you can set \(b = 0\) and \(a \geq b\).

    3. Prove that this holds for \(\lambda^{-1} \textrm{RealSoftMax}(\lambda a, \lambda b)\), provided that \(\lambda > 0\).

    4. Show that for \(\lambda \to \infty\) we have \(\lambda^{-1} \textrm{RealSoftMax}(\lambda a, \lambda b) \to \mathrm{max}(a, b)\).

    5. Construct an analogous softmin function.

    6. Extend this to more than two numbers.

  6. The function \(g(\mathbf{x}) \stackrel{\textrm{def}}{=} \log \sum_i \exp x_i\) is sometimes also referred to as the log-partition function.

    1. Prove that the function is convex. Hint: to do so, use the fact that the first derivative amounts to the probabilities from the softmax function and show that the second derivative is the variance.

    2. Show that \(g\) is translation invariant, i.e., \(g(\mathbf{x} + b) = g(\mathbf{x})\).

    3. What happens if some of the coordinates \(x_i\) are very large? What happens if they’re all very small?

    4. Show that if we choose \(b = \mathrm{max}_i x_i\) we end up with a numerically stable implementation.

  7. Assume that we have some probability distribution \(P\). Suppose we pick another distribution \(Q\) with \(Q(i) \propto P(i)^\alpha\) for \(\alpha > 0\).

    1. Which choice of \(\alpha\) corresponds to doubling the temperature? Which choice corresponds to halving it?

    2. What happens if we let the temperature approach \(0\)?

    3. What happens if we let the temperature approach \(\infty\)?

Discussions

9.3. Language Models 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.3. Language Models
Open the notebook in SageMaker Studio Lab

In Section 9.2, we saw how to map text sequences into tokens, where these tokens can be viewed as a sequence of discrete observations such as words or characters. Assume that the tokens in a text sequence of length \(T\) are in turn \(x_1, x_2, \ldots, x_T\). The goal of language models is to estimate the joint probability of the whole sequence:

(9.3.1)\[P(x_1, x_2, \ldots, x_T),\]

where statistical tools in Section 9.1 can be applied.

Language models are incredibly useful. For instance, an ideal language model should generate natural text on its own, simply by drawing one token at a time \(x_t \sim P(x_t \mid x_{t-1}, \ldots, x_1)\). Quite unlike the monkey using a typewriter, all text emerging from such a model would pass as natural language, e.g., English text. Furthermore, it would be sufficient for generating a meaningful dialog, simply by conditioning the text on previous dialog fragments. Clearly we are still very far from designing such a system, since it would need to understand the text rather than just generate grammatically sensible content.

Nonetheless, language models are of great service even in their limited form. For instance, the phrases “to recognize speech” and “to wreck a nice beach” sound very similar. This can cause ambiguity in speech recognition, which is easily resolved through a language model that rejects the second translation as outlandish. Likewise, in a document summarization algorithm it is worthwhile knowing that “dog bites man” is much more frequent than “man bites dog”, or that “I want to eat grandma” is a rather disturbing statement, whereas “I want to eat, grandma” is much more benign.

import torch
from d2l import torch as d2l

9.3.1. Learning Language Models

The obvious question is how we should model a document, or even a sequence of tokens. Suppose that we tokenize text data at the word level. Let’s start by applying basic probability rules:

(9.3.2)\[P(x_1, x_2, \ldots, x_T) = \prod_{t=1}^T P(x_t \mid x_1, \ldots, x_{t-1}).\]

For example, the probability of a text sequence containing four words would be given as:

(9.3.3)\[\begin{split}\begin{aligned}&P(\textrm{deep}, \textrm{learning}, \textrm{is}, \textrm{fun}) \\ =&P(\textrm{deep}) P(\textrm{learning} \mid \textrm{deep}) P(\textrm{is} \mid \textrm{deep}, \textrm{learning}) P(\textrm{fun} \mid \textrm{deep}, \textrm{learning}, \textrm{is}).\end{aligned}\end{split}\]

9.3.1.1. Markov Models and \(n\)-grams

Among those sequence model analyses in Section 9.1, let’s apply Markov models to language modeling. A distribution over sequences satisfies the Markov property of first order if \(P(x_{t+1} \mid x_t, \ldots, x_1) = P(x_{t+1} \mid x_t)\). Higher orders correspond to longer dependencies. This leads to a number of approximations that we could apply to model a sequence:

(9.3.4)\[\begin{split}\begin{aligned} P(x_1, x_2, x_3, x_4) &= P(x_1) P(x_2) P(x_3) P(x_4),\\ P(x_1, x_2, x_3, x_4) &= P(x_1) P(x_2 \mid x_1) P(x_3 \mid x_2) P(x_4 \mid x_3),\\ P(x_1, x_2, x_3, x_4) &= P(x_1) P(x_2 \mid x_1) P(x_3 \mid x_1, x_2) P(x_4 \mid x_2, x_3). \end{aligned}\end{split}\]

The probability formulae that involve one, two, and three variables are typically referred to as unigram, bigram, and trigram models, respectively. In order to compute the language model, we need to calculate the probability of words and the conditional probability of a word given the previous few words. Note that such probabilities are language model parameters.

9.3.1.2. Word Frequency

Here, we assume that the training dataset is a large text corpus, such as all Wikipedia entries, Project Gutenberg, and all text posted on the web. The probability of words can be calculated from the relative word frequency of a given word in the training dataset. For example, the estimate \(\hat{P}(\textrm{deep})\) can be calculated as the probability of any sentence starting with the word “deep”. A slightly less accurate approach would be to count all occurrences of the word “deep” and divide it by the total number of words in the corpus. This works fairly well, particularly for frequent words. Moving on, we could attempt to estimate

(9.3.5)\[\hat{P}(\textrm{learning} \mid \textrm{deep}) = \frac{n(\textrm{deep, learning})}{n(\textrm{deep})},\]

where \(n(x)\) and \(n(x, x')\) are the number of occurrences of singletons and consecutive word pairs, respectively. Unfortunately, estimating the probability of a word pair is somewhat more difficult, since the occurrences of “deep learning” are a lot less frequent. In particular, for some unusual word combinations it may be tricky to find enough occurrences to get accurate estimates. As suggested by the empirical results in Section 9.2.5, things take a turn for the worse for three-word combinations and beyond. There will be many plausible three-word combinations that we likely will not see in our dataset. Unless we provide some solution to assign such word combinations a nonzero count, we will not be able to use them in a language model. If the dataset is small or if the words are very rare, we might not find even a single one of them.

9.3.1.3. Laplace Smoothing

A common strategy is to perform some form of Laplace smoothing. The solution is to add a small constant to all counts. Denote by \(n\) the total number of words in the training set and \(m\) the number of unique words. This solution helps with singletons, e.g., via

(9.3.6)\[\begin{split}\begin{aligned} \hat{P}(x) & = \frac{n(x) + \epsilon_1/m}{n + \epsilon_1}, \\ \hat{P}(x' \mid x) & = \frac{n(x, x') + \epsilon_2 \hat{P}(x')}{n(x) + \epsilon_2}, \\ \hat{P}(x'' \mid x,x') & = \frac{n(x, x',x'') + \epsilon_3 \hat{P}(x'')}{n(x, x') + \epsilon_3}. \end{aligned}\end{split}\]

Here \(\epsilon_1,\epsilon_2\), and \(\epsilon_3\) are hyperparameters. Take \(\epsilon_1\) as an example: when \(\epsilon_1 = 0\), no smoothing is applied; when \(\epsilon_1\) approaches positive infinity, \(\hat{P}(x)\) approaches the uniform probability \(1/m\). The above is a rather primitive variant of what other techniques can accomplish (Wood et al., 2011).

Unfortunately, models like this get unwieldy rather quickly for the following reasons. First, as discussed in Section 9.2.5, many \(n\)-grams occur very rarely, making Laplace smoothing rather unsuitable for language modeling. Second, we need to store all counts. Third, this entirely ignores the meaning of the words. For instance, “cat” and “feline” should occur in related contexts. It is quite difficult to adjust such models to additional contexts, whereas, deep learning based language models are well suited to take this into account. Last, long word sequences are almost certain to be novel, hence a model that simply counts the frequency of previously seen word sequences is bound to perform poorly there. Therefore, we focus on using neural networks for language modeling in the rest of the chapter.

9.3.2. Perplexity

Next, let’s discuss about how to measure the quality of the language model, which we will then use to evaluate our models in the subsequent sections. One way is to check how surprising the text is. A good language model is able to predict, with high accuracy, the tokens that come next. Consider the following continuations of the phrase “It is raining”, as proposed by different language models:

  1. “It is raining outside”

  2. “It is raining banana tree”

  3. “It is raining piouw;kcj pwepoiut”

In terms of quality, Example 1 is clearly the best. The words are sensible and logically coherent. While it might not quite accurately reflect which word follows semantically (“in San Francisco” and “in winter” would have been perfectly reasonable extensions), the model is able to capture which kind of word follows. Example 2 is considerably worse by producing a nonsensical extension. Nonetheless, at least the model has learned how to spell words and some degree of correlation between words. Last, Example 3 indicates a poorly trained model that does not fit data properly.

We might measure the quality of the model by computing the likelihood of the sequence. Unfortunately this is a number that is hard to understand and difficult to compare. After all, shorter sequences are much more likely to occur than the longer ones, hence evaluating the model on Tolstoy’s magnum opus War and Peace will inevitably produce a much smaller likelihood than, say, on Saint-Exupery’s novella The Little Prince. What is missing is the equivalent of an average.

Information theory comes handy here. We defined entropy, surprisal, and cross-entropy when we introduced the softmax regression (Section 4.1.3). If we want to compress text, we can ask about predicting the next token given the current set of tokens. A better language model should allow us to predict the next token more accurately. Thus, it should allow us to spend fewer bits in compressing the sequence. So we can measure it by the cross-entropy loss averaged over all the \(n\) tokens of a sequence:

(9.3.7)\[\frac{1}{n} \sum_{t=1}^n -\log P(x_t \mid x_{t-1}, \ldots, x_1),\]

where \(P\) is given by a language model and \(x_t\) is the actual token observed at time step \(t\) from the sequence. This makes the performance on documents of different lengths comparable. For historical reasons, scientists in natural language processing prefer to use a quantity called perplexity. In a nutshell, it is the exponential of (9.3.7):

(9.3.8)\[\exp\left(-\frac{1}{n} \sum_{t=1}^n \log P(x_t \mid x_{t-1}, \ldots, x_1)\right).\]

Perplexity can be best understood as the reciprocal of the geometric mean of the number of real choices that we have when deciding which token to pick next. Let’s look at a number of cases:

  • In the best case scenario, the model always perfectly estimates the probability of the target token as 1. In this case the perplexity of the model is 1.

  • In the worst case scenario, the model always predicts the probability of the target token as 0. In this situation, the perplexity is positive infinity.

  • At the baseline, the model predicts a uniform distribution over all the available tokens of the vocabulary. In this case, the perplexity equals the number of unique tokens of the vocabulary. In fact, if we were to store the sequence without any compression, this would be the best we could do for encoding it. Hence, this provides a nontrivial upper bound that any useful model must beat.

9.3.3. Partitioning Sequences

We will design language models using neural networks and use perplexity to evaluate how good the model is at predicting the next token given the current set of tokens in text sequences. Before introducing the model, let’s assume that it processes a minibatch of sequences with predefined length at a time. Now the question is how to read minibatches of input sequences and target sequences at random.

Suppose that the dataset takes the form of a sequence of \(T\) token indices in corpus. We will partition it into subsequences, where each subsequence has \(n\) tokens (time steps). To iterate over (almost) all the tokens of the entire dataset for each epoch and obtain all possible length-\(n\) subsequences, we can introduce randomness. More concretely, at the beginning of each epoch, discard the first \(d\) tokens, where \(d\in [0,n)\) is uniformly sampled at random. The rest of the sequence is then partitioned into \(m=\lfloor (T-d)/n \rfloor\) subsequences. Denote by \(\mathbf x_t = [x_t, \ldots, x_{t+n-1}]\) the length-\(n\) subsequence starting from token \(x_t\) at time step \(t\). The resulting \(m\) partitioned subsequences are \(\mathbf x_d, \mathbf x_{d+n}, \ldots, \mathbf x_{d+n(m-1)}.\) Each subsequence will be used as an input sequence into the language model.

For language modeling, the goal is to predict the next token based on the tokens we have seen so far; hence the targets (labels) are the original sequence, shifted by one token. The target sequence for any input sequence \(\mathbf x_t\) is \(\mathbf x_{t+1}\) with length \(n\).

../_images/lang-model-data.svg

Fig. 9.3.1 Obtaining five pairs of input sequences and target sequences from partitioned length-5 subsequences.

Fig. 9.3.1 shows an example of obtaining five pairs of input sequences and target sequences with \(n=5\) and \(d=2\).

@d2l.add_to_class(d2l.TimeMachine)  #@save
def __init__(self, batch_size, num_steps, num_train=10000, num_val=5000):
    super(d2l.TimeMachine, self).__init__()
    self.save_hyperparameters()
    corpus, self.vocab = self.build(self._download())
    array = torch.tensor([corpus[i:i+num_steps+1]
                        for i in range(len(corpus)-num_steps)])
    self.X, self.Y = array[:,:-1], array[:,1:]

To train language models, we will randomly sample pairs of input sequences and target sequences in minibatches. The following data loader randomly generates a minibatch from the dataset each time. The argument batch_size specifies the number of subsequence examples in each minibatch and num_steps is the subsequence length in tokens.

@d2l.add_to_class(d2l.TimeMachine)  #@save
def get_dataloader(self, train):
    idx = slice(0, self.num_train) if train else slice(
        self.num_train, self.num_train + self.num_val)
    return self.get_tensorloader([self.X, self.Y], train, idx)

As we can see in the following, a minibatch of target sequences can be obtained by shifting the input sequences by one token.

data = d2l.TimeMachine(batch_size=2, num_steps=10)
for X, Y in data.train_dataloader():
    print('X:', X, '\nY:', Y)
    break
Downloading ../data/timemachine.txt from http://d2l-data.s3-accelerate.amazonaws.com/timemachine.txt...
X: tensor([[10,  4,  2, 21, 10, 16, 15,  0, 20,  2],
        [21,  9,  6, 19,  0, 24,  2, 26,  0, 16]])
Y: tensor([[ 4,  2, 21, 10, 16, 15,  0, 20,  2, 10],
        [ 9,  6, 19,  0, 24,  2, 26,  0, 16,  9]])

9.3.4. Summary and Discussion

Language models estimate the joint probability of a text sequence. For long sequences, \(n\)-grams provide a convenient model by truncating the dependence. However, there is a lot of structure but not enough frequency to deal efficiently with infrequent word combinations via Laplace smoothing. Thus, we will focus on neural language modeling in subsequent sections. To train language models, we can randomly sample pairs of input sequences and target sequences in minibatches. After training, we will use perplexity to measure the language model quality.

Language models can be scaled up with increased data size, model size, and amount in training compute. Large language models can perform desired tasks by predicting output text given input text instructions. As we will discuss later (e.g., Section 11.9), at the present moment large language models form the basis of state-of-the-art systems across diverse tasks.

9.3.5. Exercises

  1. Suppose there are 100,000 words in the training dataset. How much word frequency and multi-word adjacent frequency does a four-gram need to store?

  2. How would you model a dialogue?

  3. What other methods can you think of for reading long sequence data?

  4. Consider our method for discarding a uniformly random number of the first few tokens at the beginning of each epoch.

    1. Does it really lead to a perfectly uniform distribution over the sequences on the document?

    2. What would you have to do to make things even more uniform?

  5. If we want a sequence example to be a complete sentence, what kind of problem does this introduce in minibatch sampling? How can we fix it?

11.3. Attention Scoring Functions 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.

11.3. Attention Scoring Functions
Open the notebook in SageMaker Studio Lab

In Section 11.2, we used a number of different distance-based kernels, including a Gaussian kernel to model interactions between queries and keys. As it turns out, distance functions are slightly more expensive to compute than dot products. As such, with the softmax operation to ensure nonnegative attention weights, much of the work has gone into attention scoring functions \(a\) in (11.1.3) and Fig. 11.3.1 that are simpler to compute.

../_images/attention-output.svg

Fig. 11.3.1 Computing the output of attention pooling as a weighted average of values, where weights are computed with the attention scoring function \(\mathit{a}\) and the softmax operation.

import math
import torch
from torch import nn
from d2l import torch as d2l

11.3.1. Dot Product Attention

Let’s review the attention function (without exponentiation) from the Gaussian kernel for a moment:

(11.3.1)\[a(\mathbf{q}, \mathbf{k}_i) = -\frac{1}{2} \|\mathbf{q} - \mathbf{k}_i\|^2 = \mathbf{q}^\top \mathbf{k}_i -\frac{1}{2} \|\mathbf{k}_i\|^2 -\frac{1}{2} \|\mathbf{q}\|^2.\]

First, note that the final term depends on \(\mathbf{q}\) only. As such it is identical for all \((\mathbf{q}, \mathbf{k}_i)\) pairs. Normalizing the attention weights to \(1\), as is done in (11.1.3), ensures that this term disappears entirely. Second, note that both batch and layer normalization (to be discussed later) lead to activations that have well-bounded, and often constant, norms \(\|\mathbf{k}_i\|\). This is the case, for instance, whenever the keys \(\mathbf{k}_i\) were generated by a layer norm. As such, we can drop it from the definition of \(a\) without any major change in the outcome.

Last, we need to keep the order of magnitude of the arguments in the exponential function under control. Assume that all the elements of the query \(\mathbf{q} \in \mathbb{R}^d\) and the key \(\mathbf{k}_i \in \mathbb{R}^d\) are independent and identically drawn random variables with zero mean and unit variance. The dot product between both vectors has zero mean and a variance of \(d\). To ensure that the variance of the dot product still remains \(1\) regardless of vector length, we use the scaled dot product attention scoring function. That is, we rescale the dot product by \(1/\sqrt{d}\). We thus arrive at the first commonly used attention function that is used, e.g., in Transformers (Vaswani et al., 2017):

(11.3.2)\[a(\mathbf{q}, \mathbf{k}_i) = \mathbf{q}^\top \mathbf{k}_i / \sqrt{d}.\]

Note that attention weights \(\alpha\) still need normalizing. We can simplify this further via (11.1.3) by using the softmax operation:

(11.3.3)\[\alpha(\mathbf{q}, \mathbf{k}_i) = \mathrm{softmax}(a(\mathbf{q}, \mathbf{k}_i)) = \frac{\exp(\mathbf{q}^\top \mathbf{k}_i / \sqrt{d})}{\sum_{j=1} \exp(\mathbf{q}^\top \mathbf{k}_j / \sqrt{d})}.\]

As it turns out, all popular attention mechanisms use the softmax, hence we will limit ourselves to that in the remainder of this chapter.

11.3.2. Convenience Functions

We need a few functions to make the attention mechanism efficient to deploy. This includes tools for dealing with strings of variable lengths (common for natural language processing) and tools for efficient evaluation on minibatches (batch matrix multiplication).

11.3.2.1. Masked Softmax Operation

One of the most popular applications of the attention mechanism is to sequence models. Hence we need to be able to deal with sequences of different lengths. In some cases, such sequences may end up in the same minibatch, necessitating padding with dummy tokens for shorter sequences (see Section 10.5 for an example). These special tokens do not carry meaning. For instance, assume that we have the following three sentences:

Dive  into  Deep    Learning
Learn to    code    <blank>
Hello world <blank> <blank>

Since we do not want blanks in our attention model we simply need to limit \(\sum_{i=1}^n \alpha(\mathbf{q}, \mathbf{k}_i) \mathbf{v}_i\) to \(\sum_{i=1}^l \alpha(\mathbf{q}, \mathbf{k}_i) \mathbf{v}_i\) for however long, \(l \leq n\), the actual sentence is. Since it is such a common problem, it has a name: the masked softmax operation.

Let’s implement it. Actually, the implementation cheats ever so slightly by setting the values of \(\mathbf{v}_i\), for \(i > l\), to zero. Moreover, it sets the attention weights to a large negative number, such as \(-10^{6}\), in order to make their contribution to gradients and values vanish in practice. This is done since linear algebra kernels and operators are heavily optimized for GPUs and it is faster to be slightly wasteful in computation rather than to have code with conditional (if then else) statements.

def masked_softmax(X, valid_lens):  #@save
    """Perform softmax operation by masking elements on the last axis."""
    # X: 3D tensor, valid_lens: 1D or 2D tensor
    def _sequence_mask(X, valid_len, value=0):
        maxlen = X.size(1)
        mask = torch.arange((maxlen), dtype=torch.float32,
                            device=X.device)[None, :] < valid_len[:, None]
        X[~mask] = value
        return X

    if valid_lens is None:
        return nn.functional.softmax(X, dim=-1)
    else:
        shape = X.shape
        if valid_lens.dim() == 1:
            valid_lens = torch.repeat_interleave(valid_lens, shape[1])
        else:
            valid_lens = valid_lens.reshape(-1)
        # On the last axis, replace masked elements with a very large negative
        # value, whose exponentiation outputs 0
        X = _sequence_mask(X.reshape(-1, shape[-1]), valid_lens, value=-1e6)
        return nn.functional.softmax(X.reshape(shape), dim=-1)

To illustrate how this function works, consider a minibatch of two examples of size \(2 \times 4\), where their valid lengths are \(2\) and \(3\), respectively. As a result of the masked softmax operation, values beyond the valid lengths for each pair of vectors are all masked as zero.

masked_softmax(torch.rand(2, 2, 4), torch.tensor([2, 3]))
tensor([[[0.4448, 0.5552, 0.0000, 0.0000],
         [0.4032, 0.5968, 0.0000, 0.0000]],

        [[0.2795, 0.2805, 0.4400, 0.0000],
         [0.2798, 0.3092, 0.4110, 0.0000]]])

If we need more fine-grained control to specify the valid length for each of the two vectors of every example, we simply use a two-dimensional tensor of valid lengths. This yields:

masked_softmax(torch.rand(2, 2, 4), torch.tensor([[1, 3], [2, 4]]))
tensor([[[1.0000, 0.0000, 0.0000, 0.0000],
         [0.4109, 0.2794, 0.3097, 0.0000]],

        [[0.3960, 0.6040, 0.0000, 0.0000],
         [0.2557, 0.1833, 0.2420, 0.3190]]])

11.3.2.2. Batch Matrix Multiplication

Another commonly used operation is to multiply batches of matrices by one another. This comes in handy when we have minibatches of queries, keys, and values. More specifically, assume that

(11.3.4)\[\begin{split}\mathbf{Q} = [\mathbf{Q}_1, \mathbf{Q}_2, \ldots, \mathbf{Q}_n] \in \mathbb{R}^{n \times a \times b}, \\ \mathbf{K} = [\mathbf{K}_1, \mathbf{K}_2, \ldots, \mathbf{K}_n] \in \mathbb{R}^{n \times b \times c}.\end{split}\]

Then the batch matrix multiplication (BMM) computes the elementwise product

(11.3.5)\[\textrm{BMM}(\mathbf{Q}, \mathbf{K}) = [\mathbf{Q}_1 \mathbf{K}_1, \mathbf{Q}_2 \mathbf{K}_2, \ldots, \mathbf{Q}_n \mathbf{K}_n] \in \mathbb{R}^{n \times a \times c}.\]

Let’s see this in action in a deep learning framework.

Q = torch.ones((2, 3, 4))
K = torch.ones((2, 4, 6))
d2l.check_shape(torch.bmm(Q, K), (2, 3, 6))

11.3.3. Scaled Dot Product Attention

Let’s return to the dot product attention introduced in (11.3.2). In general, it requires that both the query and the key have the same vector length, say \(d\), even though this can be addressed easily by replacing \(\mathbf{q}^\top \mathbf{k}\) with \(\mathbf{q}^\top \mathbf{M} \mathbf{k}\) where \(\mathbf{M}\) is a matrix suitably chosen for translating between both spaces. For now assume that the dimensions match.

In practice, we often think of minibatches for efficiency, such as computing attention for \(n\) queries and \(m\) key-value pairs, where queries and keys are of length \(d\) and values are of length \(v\). The scaled dot product attention of queries \(\mathbf Q\in\mathbb R^{n\times d}\), keys \(\mathbf K\in\mathbb R^{m\times d}\), and values \(\mathbf V\in\mathbb R^{m\times v}\) thus can be written as

(11.3.6)\[\mathrm{softmax}\left(\frac{\mathbf Q \mathbf K^\top }{\sqrt{d}}\right) \mathbf V \in \mathbb{R}^{n\times v}.\]

Note that when applying this to a minibatch, we need the batch matrix multiplication introduced in (11.3.5). In the following implementation of the scaled dot product attention, we use dropout for model regularization.

class DotProductAttention(nn.Module):  #@save
    """Scaled dot product attention."""
    def __init__(self, dropout):
        super().__init__()
        self.dropout = nn.Dropout(dropout)

    # Shape of queries: (batch_size, no. of queries, d)
    # Shape of keys: (batch_size, no. of key-value pairs, d)
    # Shape of values: (batch_size, no. of key-value pairs, value dimension)
    # Shape of valid_lens: (batch_size,) or (batch_size, no. of queries)
    def forward(self, queries, keys, values, valid_lens=None):
        d = queries.shape[-1]
        # Swap the last two dimensions of keys with keys.transpose(1, 2)
        scores = torch.bmm(queries, keys.transpose(1, 2)) / math.sqrt(d)
        self.attention_weights = masked_softmax(scores, valid_lens)
        return torch.bmm(self.dropout(self.attention_weights), values)

To illustrate how the DotProductAttention class works, we use the same keys, values, and valid lengths from the earlier toy example for additive attention. For the purpose of our example we assume that we have a minibatch size of \(2\), a total of \(10\) keys and values, and that the dimensionality of the values is \(4\). Lastly, we assume that the valid length per observation is \(2\) and \(6\) respectively. Given that, we expect the output to be a \(2 \times 1 \times 4\) tensor, i.e., one row per example of the minibatch.

queries = torch.normal(0, 1, (2, 1, 2))
keys = torch.normal(0, 1, (2, 10, 2))
values = torch.normal(0, 1, (2, 10, 4))
valid_lens = torch.tensor([2, 6])

attention = DotProductAttention(dropout=0.5)
attention.eval()
d2l.check_shape(attention(queries, keys, values, valid_lens), (2, 1, 4))

Let’s check whether the attention weights actually vanish for anything beyond the second and sixth column respectively (because of setting the valid length to \(2\) and \(6\)).

d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)),
                  xlabel='Keys', ylabel='Queries')
../_images/output_attention-scoring-functions_722781_108_0.svg

11.3.4. Additive Attention

When queries \(\mathbf{q}\) and keys \(\mathbf{k}\) are vectors of different dimension, we can either use a matrix to address the mismatch via \(\mathbf{q}^\top \mathbf{M} \mathbf{k}\), or we can use additive attention as the scoring function. Another benefit is that, as its name indicates, the attention is additive. This can lead to some minor computational savings. Given a query \(\mathbf{q} \in \mathbb{R}^q\) and a key \(\mathbf{k} \in \mathbb{R}^k\), the additive attention scoring function (Bahdanau et al., 2014) is given by

(11.3.7)\[a(\mathbf q, \mathbf k) = \mathbf w_v^\top \textrm{tanh}(\mathbf W_q\mathbf q + \mathbf W_k \mathbf k) \in \mathbb{R},\]

where \(\mathbf W_q\in\mathbb R^{h\times q}\), \(\mathbf W_k\in\mathbb R^{h\times k}\), and \(\mathbf w_v\in\mathbb R^{h}\) are the learnable parameters. This term is then fed into a softmax to ensure both nonnegativity and normalization. An equivalent interpretation of (11.3.7) is that the query and key are concatenated and fed into an MLP with a single hidden layer. Using \(\tanh\) as the activation function and disabling bias terms, we implement additive attention as follows:

class AdditiveAttention(nn.Module):  #@save
    """Additive attention."""
    def __init__(self, num_hiddens, dropout, **kwargs):
        super(AdditiveAttention, self).__init__(**kwargs)
        self.W_k = nn.LazyLinear(num_hiddens, bias=False)
        self.W_q = nn.LazyLinear(num_hiddens, bias=False)
        self.w_v = nn.LazyLinear(1, bias=False)
        self.dropout = nn.Dropout(dropout)

    def forward(self, queries, keys, values, valid_lens):
        queries, keys = self.W_q(queries), self.W_k(keys)
        # After dimension expansion, shape of queries: (batch_size, no. of
        # queries, 1, num_hiddens) and shape of keys: (batch_size, 1, no. of
        # key-value pairs, num_hiddens). Sum them up with broadcasting
        features = queries.unsqueeze(2) + keys.unsqueeze(1)
        features = torch.tanh(features)
        # There is only one output of self.w_v, so we remove the last
        # one-dimensional entry from the shape. Shape of scores: (batch_size,
        # no. of queries, no. of key-value pairs)
        scores = self.w_v(features).squeeze(-1)
        self.attention_weights = masked_softmax(scores, valid_lens)
        # Shape of values: (batch_size, no. of key-value pairs, value
        # dimension)
        return torch.bmm(self.dropout(self.attention_weights), values)

Let’s see how AdditiveAttention works. In our toy example we pick queries, keys and values of size \((2, 1, 20)\), \((2, 10, 2)\) and \((2, 10, 4)\), respectively. This is identical to our choice for DotProductAttention, except that now the queries are \(20\)-dimensional. Likewise, we pick \((2, 6)\) as the valid lengths for the sequences in the minibatch.

queries = torch.normal(0, 1, (2, 1, 20))

attention = AdditiveAttention(num_hiddens=8, dropout=0.1)
attention.eval()
d2l.check_shape(attention(queries, keys, values, valid_lens), (2, 1, 4))

When reviewing the attention function we see a behavior that is qualitatively quite similar to that of DotProductAttention. That is, only terms within the chosen valid length \((2, 6)\) are nonzero.

d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)),
                  xlabel='Keys', ylabel='Queries')
../_images/output_attention-scoring-functions_722781_153_0.svg

11.3.5. Summary

In this section we introduced the two key attention scoring functions: dot product and additive attention. They are effective tools for aggregating across sequences of variable length. In particular, the dot product attention is the mainstay of modern Transformer architectures. When queries and keys are vectors of different lengths, we can use the additive attention scoring function instead. Optimizing these layers is one of the key areas of advance in recent years. For instance, NVIDIA’s Transformer Library and Megatron (Shoeybi et al., 2019) crucially rely on efficient variants of the attention mechanism. We will dive into this in quite a bit more detail as we review Transformers in later sections.

11.3.6. Exercises

  1. Implement distance-based attention by modifying the DotProductAttention code. Note that you only need the squared norms of the keys \(\|\mathbf{k}_i\|^2\) for an efficient implementation.

  2. Modify the dot product attention to allow for queries and keys of different dimensionalities by employing a matrix to adjust dimensions.

  3. How does the computational cost scale with the dimensionality of the keys, queries, values, and their number? What about the memory bandwidth requirements?

statistics — Mathematical statistics functions

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.

statistics — Mathematical statistics functions

Added in version 3.4.

Source code: Lib/statistics.py


This module provides functions for calculating mathematical statistics of numeric (Real-valued) data.

The module is not intended to be a competitor to third-party libraries such as NumPy, SciPy, or proprietary full-featured statistics packages aimed at professional statisticians such as Minitab, SAS and Matlab. It is aimed at the level of graphing and scientific calculators.

Unless explicitly noted, these functions support int, float, Decimal and Fraction. Behaviour with other types (whether in the numeric tower or not) is currently unsupported. Collections with a mix of types are also undefined and implementation-dependent. If your input data consists of mixed types, you may be able to use map() to ensure a consistent result, for example: map(float, input_data).

Some datasets use NaN (not a number) values to represent missing data. Since NaNs have unusual comparison semantics, they cause surprising or undefined behaviors in the statistics functions that sort data or that count occurrences. The functions affected are median(), median_low(), median_high(), median_grouped(), mode(), multimode(), and quantiles(). The NaN values should be stripped before calling these functions:

>>> from statistics import median
>>> from math import isnan
>>> from itertools import filterfalse

>>> data = [20.7, float('NaN'),19.2, 18.3, float('NaN'), 14.4]
>>> sorted(data)  # This has surprising behavior
[20.7, nan, 14.4, 18.3, 19.2, nan]
>>> median(data)  # This result is unexpected
16.35

>>> sum(map(isnan, data))    # Number of missing values
2
>>> clean = list(filterfalse(isnan, data))  # Strip NaN values
>>> clean
[20.7, 19.2, 18.3, 14.4]
>>> sorted(clean)  # Sorting now works as expected
[14.4, 18.3, 19.2, 20.7]
>>> median(clean)       # This result is now well defined
18.75

Averages and measures of central location

These functions calculate an average or typical value from a population or sample.

mean()

Arithmetic mean (“average”) of data.

fmean()

Fast, floating-point arithmetic mean, with optional weighting.

geometric_mean()

Geometric mean of data.

harmonic_mean()

Harmonic mean of data.

kde()

Estimate the probability density distribution of the data.

kde_random()

Random sampling from the PDF generated by kde().

median()

Median (middle value) of data.

median_low()

Low median of data.

median_high()

High median of data.

median_grouped()

Median (50th percentile) of grouped data.

mode()

Single mode (most common value) of discrete or nominal data.

multimode()

List of modes (most common values) of discrete or nominal data.

quantiles()

Divide data into intervals with equal probability.

Measures of spread

These functions calculate a measure of how much the population or sample tends to deviate from the typical or average values.

pstdev()

Population standard deviation of data.

pvariance()

Population variance of data.

stdev()

Sample standard deviation of data.

variance()

Sample variance of data.

Statistics for relations between two inputs

These functions calculate statistics regarding relations between two inputs.

covariance()

Sample covariance for two variables.

correlation()

Pearson and Spearman’s correlation coefficients.

linear_regression()

Slope and intercept for simple linear regression.

Function details

Note: The functions do not require the data given to them to be sorted. However, for reading convenience, most of the examples show sorted sequences.

statistics.mean(data)

Return the sample arithmetic mean of data which can be a sequence or iterable.

The arithmetic mean is the sum of the data divided by the number of data points. It is commonly called “the average”, although it is only one of many different mathematical averages. It is a measure of the central location of the data.

If data is empty, StatisticsError will be raised.

Some examples of use:

>>> mean([1, 2, 3, 4, 4])
2.8
>>> mean([-1.0, 2.5, 3.25, 5.75])
2.625

>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)

>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')

Note

The mean is strongly affected by outliers and is not necessarily a typical example of the data points. For a more robust, although less efficient, measure of central tendency, see median().

The sample mean gives an unbiased estimate of the true population mean, so that when taken on average over all the possible samples, mean(sample) converges on the true mean of the entire population. If data represents the entire population rather than a sample, then mean(data) is equivalent to calculating the true population mean μ.

statistics.fmean(data, weights=None)

Convert data to floats and compute the arithmetic mean.

This runs faster than the mean() function and it always returns a float. The data may be a sequence or iterable. If the input dataset is empty, raises a StatisticsError.

>>> fmean([3.5, 4.0, 5.25])
4.25

Optional weighting is supported. For example, a professor assigns a grade for a course by weighting quizzes at 20%, homework at 20%, a midterm exam at 30%, and a final exam at 30%:

>>> grades = [85, 92, 83, 91]
>>> weights = [0.20, 0.20, 0.30, 0.30]
>>> fmean(grades, weights)
87.6

If weights is supplied, it must be the same length as the data or a ValueError will be raised.

Added in version 3.8.

Changed in version 3.11: Added support for weights.

statistics.geometric_mean(data)

Convert data to floats and compute the geometric mean.

The geometric mean indicates the central tendency or typical value of the data using the product of the values (as opposed to the arithmetic mean which uses their sum).

Raises a StatisticsError if the input dataset is empty, if it contains a zero, or if it contains a negative value. The data may be a sequence or iterable.

No special efforts are made to achieve exact results. (However, this may change in the future.)

>>> round(geometric_mean([54, 24, 36]), 1)
36.0

Added in version 3.8.

statistics.harmonic_mean(data, weights=None)

Return the harmonic mean of data, a sequence or iterable of real-valued numbers. If weights is omitted or None, then equal weighting is assumed.

The harmonic mean is the reciprocal of the arithmetic mean() of the reciprocals of the data. For example, the harmonic mean of three values a, b and c will be equivalent to 3/(1/a + 1/b + 1/c). If one of the values is zero, the result will be zero.

The harmonic mean is a type of average, a measure of the central location of the data. It is often appropriate when averaging ratios or rates, for example speeds.

Suppose a car travels 10 km at 40 km/hr, then another 10 km at 60 km/hr. What is the average speed?

>>> harmonic_mean([40, 60])
48.0

Suppose a car travels 40 km/hr for 5 km, and when traffic clears, speeds-up to 60 km/hr for the remaining 30 km of the journey. What is the average speed?

>>> harmonic_mean([40, 60], weights=[5, 30])
56.0

StatisticsError is raised if data is empty, any element is less than zero, or if the weighted sum isn’t positive.

The current algorithm has an early-out when it encounters a zero in the input. This means that the subsequent inputs are not tested for validity. (This behavior may change in the future.)

Added in version 3.6.

Changed in version 3.10: Added support for weights.

statistics.kde(data, h, kernel='normal', *, cumulative=False)

Kernel Density Estimation (KDE): Create a continuous probability density function or cumulative distribution function from discrete samples.

The basic idea is to smooth the data using a kernel function. to help draw inferences about a population from a sample.

The degree of smoothing is controlled by the scaling parameter h which is called the bandwidth. Smaller values emphasize local features while larger values give smoother results.

The kernel determines the relative weights of the sample data points. Generally, the choice of kernel shape does not matter as much as the more influential bandwidth smoothing parameter.

Kernels that give some weight to every sample point include normal (gauss), logistic, and sigmoid.

Kernels that only give weight to sample points within the bandwidth include rectangular (uniform), triangular, parabolic (epanechnikov), quartic (biweight), triweight, and cosine.

If cumulative is true, will return a cumulative distribution function.

A StatisticsError will be raised if the data sequence is empty.

Wikipedia has an example where we can use kde() to generate and plot a probability density function estimated from a small sample:

>>> sample = [-2.1, -1.3, -0.4, 1.9, 5.1, 6.2]
>>> f_hat = kde(sample, h=1.5)
>>> xarr = [i/100 for i in range(-750, 1100)]
>>> yarr = [f_hat(x) for x in xarr]

The points in xarr and yarr can be used to make a PDF plot:

Scatter plot of the estimated probability density function.

Added in version 3.13.

statistics.kde_random(data, h, kernel='normal', *, seed=None)

Return a function that makes a random selection from the estimated probability density function produced by kde(data, h, kernel).

Providing a seed allows reproducible selections. In the future, the values may change slightly as more accurate kernel inverse CDF estimates are implemented. The seed may be an integer, float, str, or bytes.

A StatisticsError will be raised if the data sequence is empty.

Continuing the example for kde(), we can use kde_random() to generate new random selections from an estimated probability density function:

>>> data = [-2.1, -1.3, -0.4, 1.9, 5.1, 6.2]
>>> rand = kde_random(data, h=1.5, seed=8675309)
>>> new_selections = [rand() for i in range(10)]
>>> [round(x, 1) for x in new_selections]
[0.7, 6.2, 1.2, 6.9, 7.0, 1.8, 2.5, -0.5, -1.8, 5.6]

Added in version 3.13.

statistics.median(data)

Return the median (middle value) of numeric data, using the common “mean of middle two” method. If data is empty, StatisticsError is raised. data can be a sequence or iterable.

The median is a robust measure of central location and is less affected by the presence of outliers. When the number of data points is odd, the middle data point is returned:

>>> median([1, 3, 5])
3

When the number of data points is even, the median is interpolated by taking the average of the two middle values:

>>> median([1, 3, 5, 7])
4.0

This is suited for when your data is discrete, and you don’t mind that the median may not be an actual data point.

If the data is ordinal (supports order operations) but not numeric (doesn’t support addition), consider using median_low() or median_high() instead.

statistics.median_low(data)

Return the low median of numeric data. If data is empty, StatisticsError is raised. data can be a sequence or iterable.

The low median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the smaller of the two middle values is returned.

>>> median_low([1, 3, 5])
3
>>> median_low([1, 3, 5, 7])
3

Use the low median when your data are discrete and you prefer the median to be an actual data point rather than interpolated.

statistics.median_high(data)

Return the high median of data. If data is empty, StatisticsError is raised. data can be a sequence or iterable.

The high median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned.

>>> median_high([1, 3, 5])
3
>>> median_high([1, 3, 5, 7])
5

Use the high median when your data are discrete and you prefer the median to be an actual data point rather than interpolated.

statistics.median_grouped(data, interval=1.0)

Estimates the median for numeric data that has been grouped or binned around the midpoints of consecutive, fixed-width intervals.

The data can be any iterable of numeric data with each value being exactly the midpoint of a bin. At least one value must be present.

The interval is the width of each bin.

For example, demographic information may have been summarized into consecutive ten-year age groups with each group being represented by the 5-year midpoints of the intervals:

>>> from collections import Counter
>>> demographics = Counter({
...    25: 172,   # 20 to 30 years old
...    35: 484,   # 30 to 40 years old
...    45: 387,   # 40 to 50 years old
...    55:  22,   # 50 to 60 years old
...    65:   6,   # 60 to 70 years old
... })
...

The 50th percentile (median) is the 536th person out of the 1071 member cohort. That person is in the 30 to 40 year old age group.

The regular median() function would assume that everyone in the tricenarian age group was exactly 35 years old. A more tenable assumption is that the 484 members of that age group are evenly distributed between 30 and 40. For that, we use median_grouped():

>>> data = list(demographics.elements())
>>> median(data)
35
>>> round(median_grouped(data, interval=10), 1)
37.5

The caller is responsible for making sure the data points are separated by exact multiples of interval. This is essential for getting a correct result. The function does not check this precondition.

Inputs may be any numeric type that can be coerced to a float during the interpolation step.

statistics.mode(data)

Return the single most common data point from discrete or nominal data. The mode (when it exists) is the most typical value and serves as a measure of central location.

If there are multiple modes with the same frequency, returns the first one encountered in the data. If the smallest or largest of those is desired instead, use min(multimode(data)) or max(multimode(data)). If the input data is empty, StatisticsError is raised.

mode assumes discrete data and returns a single value. This is the standard treatment of the mode as commonly taught in schools:

>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3

The mode is unique in that it is the only statistic in this package that also applies to nominal (non-numeric) data:

>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'

Only hashable inputs are supported. To handle type set, consider casting to frozenset. To handle type list, consider casting to tuple. For mixed or nested inputs, consider using this slower quadratic algorithm that only depends on equality tests: max(data, key=data.count).

Changed in version 3.8: Now handles multimodal datasets by returning the first mode encountered. Formerly, it raised StatisticsError when more than one mode was found.

statistics.multimode(data)

Return a list of the most frequently occurring values in the order they were first encountered in the data. Will return more than one result if there are multiple modes or an empty list if the data is empty:

>>> multimode('aabbbbccddddeeffffgg')
['b', 'd', 'f']
>>> multimode('')
[]

Added in version 3.8.

statistics.pstdev(data, mu=None)

Return the population standard deviation (the square root of the population variance). See pvariance() for arguments and other details.

>>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
0.986893273527251
statistics.pvariance(data, mu=None)

Return the population variance of data, a non-empty sequence or iterable of real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.

If the optional second argument mu is given, it should be the population mean of the data. It can also be used to compute the second moment around a point that is not the mean. If it is missing or None (the default), the arithmetic mean is automatically calculated.

Use this function to calculate the variance from the entire population. To estimate the variance from a sample, the variance() function is usually a better choice.

Raises StatisticsError if data is empty.

Examples:

>>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
>>> pvariance(data)
1.25

If you have already calculated the mean of your data, you can pass it as the optional second argument mu to avoid recalculation:

>>> mu = mean(data)
>>> pvariance(data, mu)
1.25

Decimals and Fractions are supported:

>>> from decimal import Decimal as D
>>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('24.815')

>>> from fractions import Fraction as F
>>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
Fraction(13, 72)

Note

When called with the entire population, this gives the population variance σ². When called on a sample instead, this is the biased sample variance s², also known as variance with N degrees of freedom.

If you somehow know the true population mean μ, you may use this function to calculate the variance of a sample, giving the known population mean as the second argument. Provided the data points are a random sample of the population, the result will be an unbiased estimate of the population variance.

statistics.stdev(data, xbar=None)

Return the sample standard deviation (the square root of the sample variance). See variance() for arguments and other details.

>>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
1.0810874155219827
statistics.variance(data, xbar=None)

Return the sample variance of data, an iterable of at least two real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.

If the optional second argument xbar is given, it should be the sample mean of data. If it is missing or None (the default), the mean is automatically calculated.

Use this function when your data is a sample from a population. To calculate the variance from the entire population, see pvariance().

Raises StatisticsError if data has fewer than two values.

Examples:

>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> variance(data)
1.3720238095238095

If you have already calculated the sample mean of your data, you can pass it as the optional second argument xbar to avoid recalculation:

>>> m = mean(data)
>>> variance(data, m)
1.3720238095238095

This function does not attempt to verify that you have passed the actual mean as xbar. Using arbitrary values for xbar can lead to invalid or impossible results.

Decimal and Fraction values are supported:

>>> from decimal import Decimal as D
>>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('31.01875')

>>> from fractions import Fraction as F
>>> variance([F(1, 6), F(1, 2), F(5, 3)])
Fraction(67, 108)

Note

This is the sample variance s² with Bessel’s correction, also known as variance with N-1 degrees of freedom. Provided that the data points are representative (e.g. independent and identically distributed), the result should be an unbiased estimate of the true population variance.

If you somehow know the actual population mean μ you should pass it to the pvariance() function as the mu parameter to get the variance of a sample.

statistics.quantiles(data, *, n=4, method='exclusive')

Divide data into n continuous intervals with equal probability. Returns a list of n - 1 cut points separating the intervals.

Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate data into 100 equal sized groups. Raises StatisticsError if n is not least 1.

The data can be any iterable containing sample data. For meaningful results, the number of data points in data should be larger than n. Raises StatisticsError if there is not at least one data point.

The cut points are linearly interpolated from the two nearest data points. For example, if a cut point falls one-third of the distance between two sample values, 100 and 112, the cut-point will evaluate to 104.

The method for computing quantiles can be varied depending on whether the data includes or excludes the lowest and highest possible values from the population.

The default method is “exclusive” and is used for data sampled from a population that can have more extreme values than found in the samples. The portion of the population falling below the i-th of m sorted data points is computed as i / (m + 1). Given nine sample values, the method sorts them and assigns the following percentiles: 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%.

Setting the method to “inclusive” is used for describing population data or for samples that are known to include the most extreme values from the population. The minimum value in data is treated as the 0th percentile and the maximum value is treated as the 100th percentile. The portion of the population falling below the i-th of m sorted data points is computed as (i - 1) / (m - 1). Given 11 sample values, the method sorts them and assigns the following percentiles: 0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%.

# Decile cut points for empirically sampled data
>>> data = [105, 129, 87, 86, 111, 111, 89, 81, 108, 92, 110,
...         100, 75, 105, 103, 109, 76, 119, 99, 91, 103, 129,
...         106, 101, 84, 111, 74, 87, 86, 103, 103, 106, 86,
...         111, 75, 87, 102, 121, 111, 88, 89, 101, 106, 95,
...         103, 107, 101, 81, 109, 104]
>>> [round(q, 1) for q in quantiles(data, n=10)]
[81.0, 86.2, 89.0, 99.4, 102.5, 103.6, 106.0, 109.8, 111.0]

Added in version 3.8.

Changed in version 3.13: No longer raises an exception for an input with only a single data point. This allows quantile estimates to be built up one sample point at a time becoming gradually more refined with each new data point.

statistics.covariance(x, y, /)

Return the sample covariance of two sequence inputs x and y. Covariance is a measure of the joint variability of two inputs.

Both inputs must be of the same length (no less than two), otherwise StatisticsError is raised.

Examples:

>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> covariance(x, y)
0.75
>>> z = [9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> covariance(x, z)
-7.5
>>> covariance(z, x)
-7.5

Added in version 3.10.

statistics.correlation(x, y, /, *, method='linear')

Return the Pearson’s correlation coefficient for two sequence inputs. Pearson’s correlation coefficient r takes values between -1 and +1. It measures the strength and direction of a linear relationship.

If method is “ranked”, computes Spearman’s rank correlation coefficient for two inputs. The data is replaced by ranks. Ties are averaged so that equal values receive the same rank. The resulting coefficient measures the strength of a monotonic relationship.

Spearman’s correlation coefficient is appropriate for ordinal data or for continuous data that doesn’t meet the linear proportion requirement for Pearson’s correlation coefficient.

Both inputs must be of the same length (no less than two), and need not to be constant, otherwise StatisticsError is raised.

Example with Kepler’s laws of planetary motion:

>>> # Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and  Neptune
>>> orbital_period = [88, 225, 365, 687, 4331, 10_756, 30_687, 60_190]    # days
>>> dist_from_sun = [58, 108, 150, 228, 778, 1_400, 2_900, 4_500] # million km

>>> # Show that a perfect monotonic relationship exists
>>> correlation(orbital_period, dist_from_sun, method='ranked')
1.0

>>> # Observe that a linear relationship is imperfect
>>> round(correlation(orbital_period, dist_from_sun), 4)
0.9882

>>> # Demonstrate Kepler's third law: There is a linear correlation
>>> # between the square of the orbital period and the cube of the
>>> # distance from the sun.
>>> period_squared = [p * p for p in orbital_period]
>>> dist_cubed = [d * d * d for d in dist_from_sun]
>>> round(correlation(period_squared, dist_cubed), 4)
1.0

Added in version 3.10.

Changed in version 3.12: Added support for Spearman’s rank correlation coefficient.

statistics.linear_regression(x, y, /, *, proportional=False)

Return the slope and intercept of simple linear regression parameters estimated using ordinary least squares. Simple linear regression describes the relationship between an independent variable x and a dependent variable y in terms of this linear function:

y = slope * x + intercept + noise

where slope and intercept are the regression parameters that are estimated, and noise represents the variability of the data that was not explained by the linear regression (it is equal to the difference between predicted and actual values of the dependent variable).

Both inputs must be sequences of the same length (no less than two), and the independent variable x cannot be constant; otherwise a StatisticsError is raised.

For example, we can use the release dates of the Monty Python films to predict the cumulative number of Monty Python films that would have been produced by 2019 assuming that they had kept the pace.

>>> year = [1971, 1975, 1979, 1982, 1983]
>>> films_total = [1, 2, 3, 4, 5]
>>> slope, intercept = linear_regression(year, films_total)
>>> round(slope * 2019 + intercept)
16

If proportional is true, the independent variable x and the dependent variable y are assumed to be directly proportional. The data is fit to a line passing through the origin. Since the intercept will always be 0.0, the underlying linear function simplifies to:

y = slope * x + noise

Continuing the example from correlation(), we look to see how well a model based on major planets can predict the orbital distances for dwarf planets:

>>> model = linear_regression(period_squared, dist_cubed, proportional=True)
>>> slope = model.slope

>>> # Dwarf planets:   Pluto,  Eris,    Makemake, Haumea, Ceres
>>> orbital_periods = [90_560, 204_199, 111_845, 103_410, 1_680]  # days
>>> predicted_dist = [math.cbrt(slope * (p * p)) for p in orbital_periods]
>>> list(map(round, predicted_dist))
[5912, 10166, 6806, 6459, 414]

>>> [5_906, 10_152, 6_796, 6_450, 414]  # actual distance in million km
[5906, 10152, 6796, 6450, 414]

Added in version 3.10.

Changed in version 3.11: Added support for proportional.

Exceptions

A single exception is defined:

exception statistics.StatisticsError

Subclass of ValueError for statistics-related exceptions.

NormalDist objects

NormalDist is a tool for creating and manipulating normal distributions of a random variable. It is a class that treats the mean and standard deviation of data measurements as a single entity.

Normal distributions arise from the Central Limit Theorem and have a wide range of applications in statistics.

class statistics.NormalDist(mu=0.0, sigma=1.0)

Returns a new NormalDist object where mu represents the arithmetic mean and sigma represents the standard deviation.

If sigma is negative, raises StatisticsError.

mean

A read-only property for the arithmetic mean of a normal distribution.

median

A read-only property for the median of a normal distribution.

mode

A read-only property for the mode of a normal distribution.

stdev

A read-only property for the standard deviation of a normal distribution.

variance

A read-only property for the variance of a normal distribution. Equal to the square of the standard deviation.

classmethod from_samples(data)

Makes a normal distribution instance with mu and sigma parameters estimated from the data using fmean() and stdev().

The data can be any iterable and should consist of values that can be converted to type float. If data does not contain at least two elements, raises StatisticsError because it takes at least one point to estimate a central value and at least two points to estimate dispersion.

samples(n, *, seed=None)

Generates n random samples for a given mean and standard deviation. Returns a list of float values.

If seed is given, creates a new instance of the underlying random number generator. This is useful for creating reproducible results, even in a multi-threading context.

Changed in version 3.13.

Switched to a faster algorithm. To reproduce samples from previous versions, use random.seed() and random.gauss().

pdf(x)

Using a probability density function (pdf), compute the relative likelihood that a random variable X will be near the given value x. Mathematically, it is the limit of the ratio P(x <= X < x+dx) / dx as dx approaches zero.

The relative likelihood is computed as the probability of a sample occurring in a narrow range divided by the width of the range (hence the word “density”). Since the likelihood is relative to other points, its value can be greater than 1.0.

cdf(x)

Using a cumulative distribution function (cdf), compute the probability that a random variable X will be less than or equal to x. Mathematically, it is written P(X <= x).

inv_cdf(p)

Compute the inverse cumulative distribution function, also known as the quantile function or the percent-point function. Mathematically, it is written x : P(X <= x) = p.

Finds the value x of the random variable X such that the probability of the variable being less than or equal to that value equals the given probability p.

overlap(other)

Measures the agreement between two normal probability distributions. Returns a value between 0.0 and 1.0 giving the overlapping area for the two probability density functions.

quantiles(n=4)

Divide the normal distribution into n continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals.

Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate the normal distribution into 100 equal sized groups.

zscore(x)

Compute the Standard Score describing x in terms of the number of standard deviations above or below the mean of the normal distribution: (x - mean) / stdev.

Added in version 3.9.

Instances of NormalDist support addition, subtraction, multiplication and division by a constant. These operations are used for translation and scaling. For example:

>>> temperature_february = NormalDist(5, 2.5)             # Celsius
>>> temperature_february * (9/5) + 32                     # Fahrenheit
NormalDist(mu=41.0, sigma=4.5)

Dividing a constant by an instance of NormalDist is not supported because the result wouldn’t be normally distributed.

Since normal distributions arise from additive effects of independent variables, it is possible to add and subtract two independent normally distributed random variables represented as instances of NormalDist. For example:

>>> birth_weights = NormalDist.from_samples([2.5, 3.1, 2.1, 2.4, 2.7, 3.5])
>>> drug_effects = NormalDist(0.4, 0.15)
>>> combined = birth_weights + drug_effects
>>> round(combined.mean, 1)
3.1
>>> round(combined.stdev, 1)
0.5

Added in version 3.8.

Examples and Recipes

Classic probability problems

NormalDist readily solves classic probability problems.

For example, given historical data for SAT exams showing that scores are normally distributed with a mean of 1060 and a standard deviation of 195, determine the percentage of students with test scores between 1100 and 1200, after rounding to the nearest whole number:

>>> sat = NormalDist(1060, 195)
>>> fraction = sat.cdf(1200 + 0.5) - sat.cdf(1100 - 0.5)
>>> round(fraction * 100.0, 1)
18.4

Find the quartiles and deciles for the SAT scores:

>>> list(map(round, sat.quantiles()))
[928, 1060, 1192]
>>> list(map(round, sat.quantiles(n=10)))
[810, 896, 958, 1011, 1060, 1109, 1162, 1224, 1310]

Monte Carlo inputs for simulations

To estimate the distribution for a model that isn’t easy to solve analytically, NormalDist can generate input samples for a Monte Carlo simulation:

>>> def model(x, y, z):
...     return (3*x + 7*x*y - 5*y) / (11 * z)
...
>>> n = 100_000
>>> X = NormalDist(10, 2.5).samples(n, seed=3652260728)
>>> Y = NormalDist(15, 1.75).samples(n, seed=4582495471)
>>> Z = NormalDist(50, 1.25).samples(n, seed=6582483453)
>>> quantiles(map(model, X, Y, Z))
[1.4591308524824727, 1.8035946855390597, 2.175091447274739]

Approximating binomial distributions

Normal distributions can be used to approximate Binomial distributions when the sample size is large and when the probability of a successful trial is near 50%.

For example, an open source conference has 750 attendees and two rooms with a 500 person capacity. There is a talk about Python and another about Ruby. In previous conferences, 65% of the attendees preferred to listen to Python talks. Assuming the population preferences haven’t changed, what is the probability that the Python room will stay within its capacity limits?

>>> n = 750             # Sample size
>>> p = 0.65            # Preference for Python
>>> q = 1.0 - p         # Preference for Ruby
>>> k = 500             # Room capacity

>>> # Approximation using the cumulative normal distribution
>>> from math import sqrt
>>> round(NormalDist(mu=n*p, sigma=sqrt(n*p*q)).cdf(k + 0.5), 4)
0.8402

>>> # Exact solution using the cumulative binomial distribution
>>> from math import comb, fsum
>>> round(fsum(comb(n, r) * p**r * q**(n-r) for r in range(k+1)), 4)
0.8402

>>> # Approximation using a simulation
>>> from random import seed, binomialvariate
>>> seed(8675309)
>>> mean(binomialvariate(n, p) <= k for i in range(10_000))
0.8406

Naive bayesian classifier

Normal distributions commonly arise in machine learning problems.

Wikipedia has a nice example of a Naive Bayesian Classifier. The challenge is to predict a person’s gender from measurements of normally distributed features including height, weight, and foot size.

We’re given a training dataset with measurements for eight people. The measurements are assumed to be normally distributed, so we summarize the data with NormalDist:

>>> height_male = NormalDist.from_samples([6, 5.92, 5.58, 5.92])
>>> height_female = NormalDist.from_samples([5, 5.5, 5.42, 5.75])
>>> weight_male = NormalDist.from_samples([180, 190, 170, 165])
>>> weight_female = NormalDist.from_samples([100, 150, 130, 150])
>>> foot_size_male = NormalDist.from_samples([12, 11, 12, 10])
>>> foot_size_female = NormalDist.from_samples([6, 8, 7, 9])

Next, we encounter a new person whose feature measurements are known but whose gender is unknown:

>>> ht = 6.0        # height
>>> wt = 130        # weight
>>> fs = 8          # foot size

Starting with a 50% prior probability of being male or female, we compute the posterior as the prior times the product of likelihoods for the feature measurements given the gender:

>>> prior_male = 0.5
>>> prior_female = 0.5
>>> posterior_male = (prior_male * height_male.pdf(ht) *
...                   weight_male.pdf(wt) * foot_size_male.pdf(fs))

>>> posterior_female = (prior_female * height_female.pdf(ht) *
...                     weight_female.pdf(wt) * foot_size_female.pdf(fs))

The final prediction goes to the largest posterior. This is known as the maximum a posteriori or MAP:

>>> 'male' if posterior_male > posterior_female else 'female'
'female'

Django Tutorial Part 6: Generic list and detail views

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 6: Generic list and detail views

This tutorial extends our LocalLibrary website, adding list and detail pages for books and authors. Here we'll learn about generic class-based views, and show how they can reduce the amount of code you have to write for common use cases. We'll also go into URL handling in greater detail, showing how to perform basic pattern matching.

Prerequisites: Complete all previous tutorial topics, including Django Tutorial Part 5: Creating our home page.
Objective: To understand where and how to use generic class-based views, and how to extract patterns from URLs and pass the information to views.

Overview

In this tutorial we're going to complete the first version of the LocalLibrary website by adding list and detail pages for books and authors (or to be more precise, we'll show you how to implement the book pages, and get you to create the author pages yourself!)

The process is similar to creating the index page, which we showed in the previous tutorial. We'll still need to create URL maps, views, and templates. The main difference is that for the detail pages, we'll have the additional challenge of extracting information from patterns in the URL and passing it to the view. For these pages, we're going to demonstrate a completely different type of view: generic class-based list and detail views. These can significantly reduce the amount of view code needed, making them easier to write and maintain.

The final part of the tutorial will demonstrate how to paginate your data when using generic class-based list views.

Book list page

The book list page will display a list of all the available book records in the page, accessed using the URL: catalog/books/. The page will display a title and author for each record, with the title being a hyperlink to the associated book detail page. The page will have the same structure and navigation as all other pages in the site, and we can, therefore, extend the base template (base_generic.html) we created in the previous tutorial.

URL mapping

Open /catalog/urls.py and copy in the line setting the path for 'books/', as shown below. Just as for the index page, this path() function defines a pattern to match against the URL ('books/'), a view function that will be called if the URL matches (views.BookListView.as_view()), and a name for this particular mapping.

python
urlpatterns = [
    path('', views.index, name='index'),
    path('books/', views.BookListView.as_view(), name='books'),
]

As discussed in the previous tutorial the URL must already have matched /catalog, so the view will actually be called for the URL: /catalog/books/.

The view function has a different format than before — that's because this view will actually be implemented as a class. We will be inheriting from an existing generic view function that already does most of what we want this view function to do, rather than writing our own from scratch.

For Django class-based views we access an appropriate view function by calling the class method as_view(). This does all the work of creating an instance of the class, and making sure that the right handler methods are called for incoming HTTP requests.

View (class-based)

We could quite easily write the book list view as a regular function (just like our previous index view), which would query the database for all books, and then call render() to pass the list to a specified template. Instead, however, we're going to use a class-based generic list view (ListView) — a class that inherits from an existing view. Because the generic view already implements most of the functionality we need and follows Django best-practice, we will be able to create a more robust list view with less code, less repetition, and ultimately less maintenance.

Open catalog/views.py, and copy the following code into the bottom of the file:

python
from django.views import generic

class BookListView(generic.ListView):
    model = Book

That's it! The generic view will query the database to get all records for the specified model (Book) then render a template located at /django-locallibrary-tutorial/catalog/templates/catalog/book_list.html (which we will create below). Within the template you can access the list of books with the template variable named object_list OR book_list (i.e., generically <the model name>_list).

Note: This awkward path for the template location isn't a misprint — the generic views look for templates in /application_name/the_model_name_list.html (catalog/book_list.html in this case) inside the application's /application_name/templates/ directory (/catalog/templates/).

You can add attributes to change the default behavior above. For example, you can specify another template file if you need to have multiple views that use this same model, or you might want to use a different template variable name if book_list is not intuitive for your particular template use-case. Possibly the most useful variation is to change/filter the subset of results that are returned — so instead of listing all books you might list top 5 books that were read by other users.

python
class BookListView(generic.ListView):
    model = Book
    context_object_name = 'book_list'   # your own name for the list as a template variable
    queryset = Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war
    template_name = 'books/my_arbitrary_template_name_list.html'  # Specify your own template name/location

Overriding methods in class-based views

While we don't need to do so here, you can also override some of the class methods.

For example, we can override the get_queryset() method to change the list of records returned. This is more flexible than just setting the queryset attribute as we did in the preceding code fragment (though there is no real benefit in this case):

python
class BookListView(generic.ListView):
    model = Book

    def get_queryset(self):
        return Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war

We might also override get_context_data() in order to pass additional context variables to the template (e.g., the list of books is passed by default). The fragment below shows how to add a variable named some_data to the context (it would then be available as a template variable).

python
class BookListView(generic.ListView):
    model = Book

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get the context
        context = super(BookListView, self).get_context_data(**kwargs)
        # Create any data and add it to the context
        context['some_data'] = 'This is just some data'
        return context

When doing this it is important to follow the pattern used above:

  • First get the existing context from our superclass.
  • Then add your new context information.
  • Then return the new (updated) context.

Note: Check out Built-in class-based generic views (Django docs) for many more examples of what you can do.

Creating the List View template

Create the HTML file /django-locallibrary-tutorial/catalog/templates/catalog/book_list.html and copy in the text below. As discussed above, this is the default template file expected by the generic class-based list view (for a model named Book in an application named catalog).

Templates for generic views are just like any other templates (although of course the context/information passed to the template may differ). As with our index template, we extend our base template in the first line and then replace the block named content.

django
{% extends "base_generic.html" %}

{% block content %}
  <h1>Book List</h1>
  {% if book_list %}
    <ul>
      {% for book in book_list %}
      <li>
        <a href="{{ book.get_absolute_url }}">{{ book.title }}</a>
        ({{book.author}})
      </li>
      {% endfor %}
    </ul>
  {% else %}
    <p>There are no books in the library.</p>
  {% endif %}
{% endblock %}

The view passes the context (list of books) by default as object_list and book_list aliases; either will work.

Conditional execution

We use the if, else, and endif template tags to check whether the book_list has been defined and is not empty. If book_list is empty, then the else clause displays text explaining that there are no books to list. If book_list is not empty, then we iterate through the list of books.

django
{% if book_list %}
  <!-- code here to list the books -->
{% else %}
  <p>There are no books in the library.</p>
{% endif %}

The condition above only checks for one case, but you can test on additional conditions using the elif template tag (e.g., {% elif var2 %}). For more information about conditional operators see: if, ifequal/ifnotequal, and ifchanged in Built-in template tags and filters (Django Docs).

For loops

The template uses the for and endfor template tags to loop through the book list, as shown below. Each iteration populates the book template variable with information for the current list item.

django
{% for book in book_list %}
  <li><!-- code here get information from each book item --></li>
{% endfor %}

You might also use the {% empty %} template tag to define what happens if the book list is empty (although our template chooses to use a conditional instead):

django
<ul>
  {% for book in book_list %}
    <li><!-- code here get information from each book item --></li>
  {% empty %}
    <p>There are no books in the library.</p>
  {% endfor %}
</ul>

While not used here, within the loop Django will also create other variables that you can use to track the iteration. For example, you can test the forloop.last variable to perform conditional processing the last time that the loop is run.

Accessing variables

The code inside the loop creates a list item for each book that shows both the title (as a link to the yet-to-be-created detail view) and the author.

django
<a href="{{ book.get_absolute_url }}">{{ book.title }}</a> ({{book.author}})

We access the fields of the associated book record using the "dot notation" (e.g., book.title and book.author), where the text following the book item is the field name (as defined in the model).

We can also call functions in the model from within our template — in this case we call Book.get_absolute_url() to get a URL you could use to display the associated detail record. This works provided the function does not have any arguments (there is no way to pass arguments!)

Note: We have to be a little careful of "side effects" when calling functions in templates. Here we just get a URL to display, but a function can do pretty much anything — we wouldn't want to delete our database (for example) just by rendering our template!

Update the base template

Open the base template (/django-locallibrary-tutorial/catalog/templates/base_generic.html) and insert {% url 'books' %} into the URL link for All books, as shown below. This will enable the link in all pages (we can successfully put this in place now that we've created the "books" URL mapper).

django
<li><a href="{% url 'index' %}">Home</a></li>
<li><a href="{% url 'books' %}">All books</a></li>
<li><a href="">All authors</a></li>

What does it look like?

You won't be able to build the book list yet, because we're still missing a dependency — the URL map for the book detail pages, which is needed to create hyperlinks to individual books. We'll show both list and detail views after the next section.

Book detail page

The book detail page will display information about a specific book, accessed using the URL catalog/book/<id> (where <id> is the primary key for the book). In addition to fields in the Book model (author, summary, ISBN, language, and genre), we'll also list the details of the available copies (BookInstances) including the status, expected return date, imprint, and id. This will allow our readers to not only learn about the book, but also to confirm whether/when it is available.

URL mapping

Open /catalog/urls.py and add the path named 'book-detail' shown below. This path() function defines a pattern, associated generic class-based detail view, and a name.

python
urlpatterns = [
    path('', views.index, name='index'),
    path('books/', views.BookListView.as_view(), name='books'),
    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
]

For the book-detail path the URL pattern uses a special syntax to capture the specific id of the book that we want to see. The syntax is very simple: angle brackets define the part of the URL to be captured, enclosing the name of the variable that the view can use to access the captured data. For example, <something>, will capture the marked pattern and pass the value to the view as a variable "something". You can optionally precede the variable name with a converter specification that defines the type of data (int, str, slug, uuid, path).

In this case we use '<int:pk>' to capture the book id, which must be a specially formatted string and pass it to the view as a parameter named pk (short for primary key). This is the id that is being used to store the book uniquely in the database, as defined in the Book Model.

Note: As discussed previously, our matched URL is actually catalog/book/<digits> (because we are in the catalog application, /catalog/ is assumed).

Warning: The generic class-based detail view expects to be passed a parameter named pk. If you're writing your own function view you can use whatever parameter name you like, or indeed pass the information in an unnamed argument.

Advanced path matching/regular expression primer

Note: You won't need this section to complete the tutorial! We provide it because knowing this option is likely to be useful in your Django-centric future.

The pattern matching provided by path() is simple and useful for the (very common) cases where you just want to capture any string or integer. If you need more refined filtering (for example, to filter only strings that have a certain number of characters) then you can use the re_path() method.

This method is used just like path() except that it allows you to specify a pattern using a Regular expression. For example, the previous path could have been written as shown below:

python
re_path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),

Regular expressions are an incredibly powerful pattern mapping tool. They are, frankly, quite unintuitive and can be intimidating for beginners. Below is a very short primer!

The first thing to know is that regular expressions should usually be declared using the raw string literal syntax (i.e., they are enclosed as shown: r'<your regular expression text goes here>').

The main parts of the syntax you will need to know for declaring the pattern matches are:

Symbol Meaning
^ Match the beginning of the text
$ Match the end of the text
\d Match a digit (0, 1, 2, … 9)
\w Match a word character, e.g., any upper- or lower-case character in the alphabet, digit or the underscore character (_)
+ Match one or more of the preceding character. For example, to match one or more digits you would use \d+. To match one or more "a" characters, you could use a+
* Match zero or more of the preceding character. For example, to match nothing or a word you could use \w*
( ) Capture the part of the pattern inside the parentheses. Any captured values will be passed to the view as unnamed parameters (if multiple patterns are captured, the associated parameters will be supplied in the order that the captures were declared).
(?P<name>...) Capture the pattern (indicated by ...) as a named variable (in this case "name"). The captured values are passed to the view with the name specified. Your view must therefore declare a parameter with the same name!
[ ] Match against one character in the set. For example, [abc] will match on 'a' or 'b' or 'c'. [-\w] will match on the '-' character or any word character.

Most other characters can be taken literally!

Let's consider a few real examples of patterns:

Pattern Description
r'^book/(?P<pk>\d+)$'

This is the RE used in our URL mapper. It matches a string that has book/ at the start of the line (^book/), then has one or more digits (\d+), and then ends (with no non-digit characters before the end of line marker).

It also captures all the digits (?P<pk>\d+) and passes them to the view in a parameter named 'pk'. The captured values are always passed as a string!

For example, this would match book/1234, and send a variable pk='1234' to the view.

r'^book/(\d+)$' This matches the same URLs as the preceding case. The captured information would be sent as an unnamed argument to the view.
r'^book/(?P<stub>[-\w]+)$'

This matches a string that has book/ at the start of the line (^book/), then has one or more characters that are either a '-' or a word character ([-\w]+), and then ends. It also captures this set of characters and passes them to the view in a parameter named 'stub'.

This is a fairly typical pattern for a "stub". Stubs are URL-friendly word-based primary keys for data. You might use a stub if you wanted your book URL to be more informative. For example /catalog/book/the-secret-garden rather than /catalog/book/33.

You can capture multiple patterns in the one match, and hence encode lots of different information in a URL.

Note: As a challenge, consider how you might encode a URL to list all books released in a particular year, month, day, and the RE that could be used to match it.

Passing additional options in your URL maps

One feature that we haven't used here, but which you may find valuable, is that you can pass a dictionary containing additional options to the view (using the third un-named argument to the path() function). This approach can be useful if you want to use the same view for multiple resources, and pass data to configure its behavior in each case.

For example, given the path shown below, for a request to /my-url/halibut/ Django will call views.my_view(request, fish='halibut', my_template_name='some_path').

python
path('my-url/<fish>', views.my_view, {'my_template_name': 'some_path'}, name='aurl'),

Note: Both named captured patterns and dictionary options are passed to the view as named arguments. If you use the same name for both a capture pattern and a dictionary key, then the dictionary option will be used.

View (class-based)

Open catalog/views.py, and copy the following code into the bottom of the file:

python
class BookDetailView(generic.DetailView):
    model = Book

That's it! All you need to do now is create a template called /django-locallibrary-tutorial/catalog/templates/catalog/book_detail.html, and the view will pass it the database information for the specific Book record extracted by the URL mapper. Within the template you can access the book's details with the template variable named object OR book (i.e., generically the_model_name).

If you need to, you can change the template used and the name of the context object used to reference the book in the template. You can also override methods to, for example, add additional information to the context.

What happens if the record doesn't exist?

If a requested record does not exist then the generic class-based detail view will raise an Http404 exception for you automatically — in production, this will automatically display an appropriate "resource not found" page, which you can customize if desired.

Just to give you some idea of how this works, the code fragment below demonstrates how you would implement the class-based view as a function if you were not using the generic class-based detail view.

python
def book_detail_view(request, primary_key):
    try:
        book = Book.objects.get(pk=primary_key)
    except Book.DoesNotExist:
        raise Http404('Book does not exist')

    return render(request, 'catalog/book_detail.html', context={'book': book})

The view first tries to get the specific book record from the model. If this fails the view should raise an Http404 exception to indicate that the book is "not found". The final step is then, as usual, to call render() with the template name and the book data in the context parameter (as a dictionary).

Another way you could do this if you were not using a generic view would be to call the get_object_or_404() function. This is a shortcut to raise an Http404 exception if the record is not found.

python
from django.shortcuts import get_object_or_404

def book_detail_view(request, primary_key):
    book = get_object_or_404(Book, pk=primary_key)
    return render(request, 'catalog/book_detail.html', context={'book': book})

Creating the Detail View template

Create the HTML file /django-locallibrary-tutorial/catalog/templates/catalog/book_detail.html and give it the below content. As discussed above, this is the default template file name expected by the generic class-based detail view (for a model named Book in an application named catalog).

django
{% extends "base_generic.html" %}

{% block content %}
  <h1>Title: {{ book.title }}</h1>

  <p><strong>Author:</strong> <a href="">{{ book.author }}</a></p>
  <!-- author detail link not yet defined -->
  <p><strong>Summary:</strong> {{ book.summary }}</p>
  <p><strong>ISBN:</strong> {{ book.isbn }}</p>
  <p><strong>Language:</strong> {{ book.language }}</p>
  <p><strong>Genre:</strong> {{ book.genre.all|join:", " }}</p>

  <div style="margin-left:20px;margin-top:20px">
    <h4>Copies</h4>

    {% for copy in book.bookinstance_set.all %}
      <hr />
      <p
        class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'm' %}text-danger{% else %}text-warning{% endif %}">
        {{ copy.get_status_display }}
      </p>
      {% if copy.status != 'a' %}
        <p><strong>Due to be returned:</strong> {{ copy.due_back }}</p>
      {% endif %}
      <p><strong>Imprint:</strong> {{ copy.imprint }}</p>
      <p class="text-muted"><strong>Id:</strong> {{ copy.id }}</p>
    {% endfor %}
  </div>
{% endblock %}

Note: The author link in the template above has an empty URL because we've not yet created an author detail page to link to. Once the detail page exists we can get its URL with either of these two approaches:

  • Use the url template tag to reverse the 'author-detail' URL (defined in the URL mapper), passing it the author instance for the book:

    django
    <a href="{% url 'author-detail' book.author.pk %}">{{ book.author }}</a>
    
  • Call the author model's get_absolute_url() method (this performs the same reversing operation):

    django
    <a href="{{ book.author.get_absolute_url }}">{{ book.author }}</a>
    

While both methods effectively do the same thing, get_absolute_url() is preferred because it helps you write more consistent and maintainable code (any changes only need to be done in one place: the author model).

Though a little larger, almost everything in this template has been described previously:

  • We extend our base template and override the "content" block.
  • We use conditional processing to determine whether or not to display specific content.
  • We use for loops to loop through lists of objects.
  • We access the context fields using the dot notation (because we've used the detail generic view, the context is named book; we could also use object)

The first interesting thing we haven't seen before is the function book.bookinstance_set.all(). This method is "automagically" constructed by Django in order to return the set of BookInstance records associated with a particular Book.

django
{% for copy in book.bookinstance_set.all %}
  <!-- code to iterate across each copy/instance of a book -->
{% endfor %}

This method is needed because you declare a ForeignKey (one-to many) field only in the "many" side of the relationship (the BookInstance). Since you don't do anything to declare the relationship in the other ("one") model, it (the Book) doesn't have any field to get the set of associated records. To overcome this problem, Django constructs an appropriately named "reverse lookup" function that you can use. The name of the function is constructed by lower-casing the model name where the ForeignKey was declared, followed by _set (i.e., so the function created in Book is bookinstance_set()).

Note: Here we use all() to get all records (the default). While you can use the filter() method to get a subset of records in code, you can't do this directly in templates because you can't specify arguments to functions.

Beware also that if you don't define an order (on your class-based view or model), you will also see errors from the development server like this one:

[29/May/2017 18:37:53] "GET /catalog/books/?page=1 HTTP/1.1" 200 1637
/foo/local_library/venv/lib/python3.5/site-packages/django/views/generic/list.py:99: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <QuerySet [<Author: Ortiz, David>, <Author: H. McRaven, William>, <Author: Leigh, Melinda>]>
  allow_empty_first_page=allow_empty_first_page, **kwargs)

That happens because the paginator object expects to see some ORDER BY being executed on your underlying database. Without it, it can't be sure the records being returned are actually in the right order!

This tutorial hasn't covered Pagination (yet!), but since you can't use sort_by() and pass a parameter (the same with filter() described above) you will have to choose between three choices:

  1. Add an ordering inside a class Meta declaration on your model.
  2. Add a queryset attribute in your custom class-based view, specifying an order_by().
  3. Adding a get_queryset method to your custom class-based view and also specify the order_by().

If you decide to go with a class Meta for the Author model (probably not as flexible as customizing the class-based view, but easy enough), you will end up with something like this:

python
class Author(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_death = models.DateField('Died', null=True, blank=True)

    def get_absolute_url(self):
        return reverse('author-detail', args=[str(self.id)])

    def __str__(self):
        return f'{self.last_name}, {self.first_name}'

    class Meta:
        ordering = ['last_name']

Of course, the field doesn't need to be last_name: it could be any other.

Last but not least, you should sort by an attribute/column that actually has an index (unique or not) on your database to avoid performance issues. Of course, this will not be necessary here (we are probably getting ahead of ourselves with so few books and users), but it is something worth keeping in mind for future projects.

The second interesting (and non-obvious) thing in the template is where we display the status text for each book instance ("available", "maintenance", etc.). Astute readers will note that the method BookInstance.get_status_display() that we use to get the status text does not appear elsewhere in the code.

django
 <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'm' %}text-danger{% else %}text-warning{% endif %}">
 {{ copy.get_status_display }} </p>

This function is automatically created because BookInstance.status is a choices field. Django automatically creates a method get_foo_display() for every choices field foo in a model, which can be used to get the current value of the field.

What does it look like?

At this point, we should have created everything needed to display both the book list and book detail pages. Run the server (python3 manage.py runserver) and open your browser to http://127.0.0.1:8000/.

Warning: Don't click any author or author detail links yet — you'll create those in the challenge!

Click the All books link to display the list of books.

Book List Page

Then click a link to one of your books. If everything is set up correctly, you should see something like the following screenshot.

Book Detail Page

Pagination

If you've just got a few records, our book list page will look fine. However, as you get into the tens or hundreds of records the page will take progressively longer to load (and have far too much content to browse sensibly). The solution to this problem is to add pagination to your list views, reducing the number of items displayed on each page.

Django has excellent inbuilt support for pagination. Even better, this is built into the generic class-based list views so you don't have to do very much to enable it!

Views

Open catalog/views.py, and add the paginate_by line shown below.

python
class BookListView(generic.ListView):
    model = Book
    paginate_by = 10

With this addition, as soon as you have more than 10 records the view will start paginating the data it sends to the template. The different pages are accessed using GET parameters — to access page 2 you would use the URL /catalog/books/?page=2.

Templates

Now that the data is paginated, we need to add support to the template to scroll through the results set. Because we might want paginate all list views, we'll add this to the base template.

Open /django-locallibrary-tutorial/catalog/templates/base_generic.html and find the "content block" (as shown below).

django
{% block content %}{% endblock %}

Copy in the following pagination block immediately following the {% endblock %}. The code first checks if pagination is enabled on the current page. If so, it adds next and previous links as appropriate (and the current page number).

django
{% block pagination %}
    {% if is_paginated %}
        <div class="pagination">
            <span class="page-links">
                {% if page_obj.has_previous %}
                    <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a>
                {% endif %}
                <span class="page-current">
                    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
                </span>
                {% if page_obj.has_next %}
                    <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a>
                {% endif %}
            </span>
        </div>
    {% endif %}
  {% endblock %}

The page_obj is a Paginator object that will exist if pagination is being used on the current page. It allows you to get all the information about the current page, previous pages, how many pages there are, etc.

We use {{ request.path }} to get the current page URL for creating the pagination links. This is useful because it is independent of the object that we're paginating.

That's it!

What does it look like?

The screenshot below shows what the pagination looks like — if you haven't entered more than 10 titles into your database, then you can test it more easily by lowering the number specified in the paginate_by line in your catalog/views.py file. To get the below result we changed it to paginate_by = 2.

The pagination links are displayed on the bottom, with next/previous links being displayed depending on which page you're on.

Book List Page - paginated

Challenge yourself

The challenge in this article is to create the author detail and list views required to complete the project. These should be made available at the following URLs:

  • catalog/authors/ — The list of all authors.
  • catalog/author/<id> — The detail view for the specific author with a primary key field named <id>

The code required for the URL mappers and the views should be virtually identical to the Book list and detail views we created above. The templates will be different but will share similar behavior.

Note:

  • Once you've created the URL mapper for the author list page you will also need to update the All authors link in the base template. Follow the same process as we did when we updated the All books link.

  • Once you've created the URL mapper for the author detail page, you should also update the book detail view template (/django-locallibrary-tutorial/catalog/templates/catalog/book_detail.html) so that the author link points to your new author detail page (rather than being an empty URL). The recommended way to do this is to call get_absolute_url() on the author model as shown below.

    django
    <p>
      <strong>Author:</strong>
      <a href="{{ book.author.get_absolute_url }}">{{ book.author }}</a>
    </p>
    

When you are finished, your pages should look something like the screenshots below.

Author List Page

Author Detail Page

Summary

Congratulations, our basic library functionality is now complete!

In this article, we've learned how to use the generic class-based list and detail views and used them to create pages to view our books and authors. Along the way we've learned about pattern matching with regular expressions, and how you can pass data from URLs to your views. We've also learned a few more tricks for using templates. Last of all we've shown how to paginate list views so that our lists are manageable even when we have many records.

In our next articles, we'll extend this library to support user accounts, and thereby demonstrate user authentication, permissions, sessions, and forms.

See also