Complete Assigned Readings

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

8. Errors and Exceptions

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.

8. Errors and Exceptions

Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.

8.1. Syntax Errors

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:

>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
               ^^^^^
SyntaxError: invalid syntax

The parser repeats the offending line and displays little arrows pointing at the place where the error was detected. Note that this is not always the place that needs to be fixed. In the example, the error is detected at the function print(), since a colon (':') is missing just before it.

The file name (<stdin> in our example) and line number are printed so you know where to look in case the input came from a file.

8.2. Exceptions

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here:

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    10 * (1/0)
          ~^~
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    4 + spam*3
        ^^^^
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    '2' + 2
    ~~~~^~~
TypeError: can only concatenate str (not "int") to str

The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError. The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords).

The rest of the line provides detail based on the type of exception and what caused it.

The preceding part of the error message shows the context where the exception occurred, in the form of a stack traceback. In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input.

Built-in Exceptions lists the built-in exceptions and their meanings.

8.3. Handling Exceptions

It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.

>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
...

The try statement works as follows.

  • First, the try clause (the statement(s) between the try and except keywords) is executed.

  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.

  • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.

  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with an error message.

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions, for example:

... except RuntimeError, TypeError, NameError:
...     pass

A class in an except clause matches exceptions which are instances of the class itself or one of its derived classes (but not the other way around — an except clause listing a derived class does not match instances of its base classes). For example, the following code will print B, C, D in that order:

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")

Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered.

When an exception occurs, it may have associated values, also known as the exception’s arguments. The presence and types of the arguments depend on the exception type.

The except clause may specify a variable after the exception name. The variable is bound to the exception instance which typically has an args attribute that stores the arguments. For convenience, builtin exception types define __str__() to print all the arguments without explicitly accessing .args.

>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception type
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

The exception’s __str__() output is printed as the last part (‘detail’) of the message for unhandled exceptions.

BaseException is the common base class of all exceptions. One of its subclasses, Exception, is the base class of all the non-fatal exceptions. Exceptions which are not subclasses of Exception are not typically handled, because they are used to indicate that the program should terminate. They include SystemExit which is raised by sys.exit() and KeyboardInterrupt which is raised when a user wishes to interrupt the program.

Exception can be used as a wildcard that catches (almost) everything. However, it is good practice to be as specific as possible with the types of exceptions that we intend to handle, and to allow any unexpected exceptions to propagate on.

The most common pattern for handling Exception is to print or log the exception and then re-raise it (allowing a caller to handle the exception as well):

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error:", err)
except ValueError:
    print("Could not convert data to an integer.")
except Exception as err:
    print(f"Unexpected {err=}, {type(err)=}")
    raise

The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except OSError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.

Exception handlers do not handle only exceptions that occur immediately in the try clause, but also those that occur inside functions that are called (even indirectly) in the try clause. For example:

>>> def this_fails():
...     x = 1/0
...
>>> try:
...     this_fails()
... except ZeroDivisionError as err:
...     print('Handling run-time error:', err)
...
Handling run-time error: division by zero

8.4. Raising Exceptions

The raise statement allows the programmer to force a specified exception to occur. For example:

>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    raise NameError('HiThere')
NameError: HiThere

The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from BaseException, such as Exception or one of its subclasses). If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments:

raise ValueError  # shorthand for 'raise ValueError()'

If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:

>>> try:
...     raise NameError('HiThere')
... except NameError:
...     print('An exception flew by!')
...     raise
...
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    raise NameError('HiThere')
NameError: HiThere

8.5. Exception Chaining

If an unhandled exception occurs inside an except section, it will have the exception being handled attached to it and included in the error message:

>>> try:
...     open("database.sqlite")
... except OSError:
...     raise RuntimeError("unable to handle error")
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    open("database.sqlite")
    ~~~~^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
    raise RuntimeError("unable to handle error")
RuntimeError: unable to handle error

To indicate that an exception is a direct consequence of another, the raise statement allows an optional from clause:

# exc must be exception instance or None.
raise RuntimeError from exc

This can be useful when you are transforming exceptions. For example:

>>> def func():
...     raise ConnectionError
...
>>> try:
...     func()
... except ConnectionError as exc:
...     raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    func()
    ~~~~^^
  File "<stdin>", line 2, in func
ConnectionError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
    raise RuntimeError('Failed to open database') from exc
RuntimeError: Failed to open database

It also allows disabling automatic exception chaining using the from None idiom:

>>> try:
...     open('database.sqlite')
... except OSError:
...     raise RuntimeError from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
    raise RuntimeError from None
RuntimeError

For more information about chaining mechanics, see Built-in Exceptions.

8.6. User-defined Exceptions

Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derived from the Exception class, either directly or indirectly.

Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception.

Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions.

Many standard modules define their own exceptions to report errors that may occur in functions they define.

8.7. Defining Clean-up Actions

The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:

>>> try:
...     raise KeyboardInterrupt
... finally:
...     print('Goodbye, world!')
...
Goodbye, world!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    raise KeyboardInterrupt
KeyboardInterrupt

If a finally clause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception. The following points discuss more complex cases when an exception occurs:

  • If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.

  • An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.

  • If the finally clause executes a break, continue or return statement, exceptions are not re-raised. This can be confusing and is therefore discouraged. From version 3.14 the compiler emits a SyntaxWarning for it (see PEP 765).

  • If the try statement reaches a break, continue or return statement, the finally clause will execute just prior to the break, continue or return statement’s execution.

  • If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement. This can be confusing and is therefore discouraged. From version 3.14 the compiler emits a SyntaxWarning for it (see PEP 765).

For example:

>>> def bool_return():
...     try:
...         return True
...     finally:
...         return False
...
>>> bool_return()
False

A more complicated example:

>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print("division by zero!")
...     else:
...         print("result is", result)
...     finally:
...         print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    divide("2", "1")
    ~~~~~~^^^^^^^^^^
  File "<stdin>", line 3, in divide
    result = x / y
             ~~^~~
TypeError: unsupported operand type(s) for /: 'str' and 'str'

As you can see, the finally clause is executed in any event. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed.

In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.

8.8. Predefined Clean-up Actions

Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. Look at the following example, which tries to open a file and print its contents to the screen.

for line in open("myfile.txt"):
    print(line, end="")

The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.

with open("myfile.txt") as f:
    for line in f:
        print(line, end="")

After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. Objects which, like files, provide predefined clean-up actions will indicate this in their documentation.

8.9. Raising and Handling Multiple Unrelated Exceptions

There are situations where it is necessary to report several exceptions that have occurred. This is often the case in concurrency frameworks, when several tasks may have failed in parallel, but there are also other use cases where it is desirable to continue execution and collect multiple errors rather than raise the first exception.

The builtin ExceptionGroup wraps a list of exception instances so that they can be raised together. It is an exception itself, so it can be caught like any other exception.

>>> def f():
...     excs = [OSError('error 1'), SystemError('error 2')]
...     raise ExceptionGroup('there were problems', excs)
...
>>> f()
  + Exception Group Traceback (most recent call last):
  |   File "<stdin>", line 1, in <module>
  |     f()
  |     ~^^
  |   File "<stdin>", line 3, in f
  |     raise ExceptionGroup('there were problems', excs)
  | ExceptionGroup: there were problems (2 sub-exceptions)
  +-+---------------- 1 ----------------
    | OSError: error 1
    +---------------- 2 ----------------
    | SystemError: error 2
    +------------------------------------
>>> try:
...     f()
... except Exception as e:
...     print(f'caught {type(e)}: {e}')
...
caught <class 'ExceptionGroup'>: there were problems (2 sub-exceptions)
>>>

By using except* instead of except, we can selectively handle only the exceptions in the group that match a certain type. In the following example, which shows a nested exception group, each except* clause extracts from the group exceptions of a certain type while letting all other exceptions propagate to other clauses and eventually to be reraised.

>>> def f():
...     raise ExceptionGroup(
...         "group1",
...         [
...             OSError(1),
...             SystemError(2),
...             ExceptionGroup(
...                 "group2",
...                 [
...                     OSError(3),
...                     RecursionError(4)
...                 ]
...             )
...         ]
...     )
...
>>> try:
...     f()
... except* OSError as e:
...     print("There were OSErrors")
... except* SystemError as e:
...     print("There were SystemErrors")
...
There were OSErrors
There were SystemErrors
  + Exception Group Traceback (most recent call last):
  |   File "<stdin>", line 2, in <module>
  |     f()
  |     ~^^
  |   File "<stdin>", line 2, in f
  |     raise ExceptionGroup(
  |     ...<12 lines>...
  |     )
  | ExceptionGroup: group1 (1 sub-exception)
  +-+---------------- 1 ----------------
    | ExceptionGroup: group2 (1 sub-exception)
    +-+---------------- 1 ----------------
      | RecursionError: 4
      +------------------------------------
>>>

Note that the exceptions nested in an exception group must be instances, not types. This is because in practice the exceptions would typically be ones that have already been raised and caught by the program, along the following pattern:

>>> excs = []
... for test in tests:
...     try:
...         test.run()
...     except Exception as e:
...         excs.append(e)
...
>>> if excs:
...    raise ExceptionGroup("Test Failures", excs)
...

8.10. Enriching Exceptions with Notes

When an exception is created in order to be raised, it is usually initialized with information that describes the error that has occurred. There are cases where it is useful to add information after the exception was caught. For this purpose, exceptions have a method add_note(note) that accepts a string and adds it to the exception’s notes list. The standard traceback rendering includes all notes, in the order they were added, after the exception.

>>> try:
...     raise TypeError('bad type')
... except Exception as e:
...     e.add_note('Add some information')
...     e.add_note('Add some more information')
...     raise
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    raise TypeError('bad type')
TypeError: bad type
Add some information
Add some more information
>>>

For example, when collecting exceptions into an exception group, we may want to add context information for the individual errors. In the following each exception in the group has a note indicating when this error has occurred.

>>> def f():
...     raise OSError('operation failed')
...
>>> excs = []
>>> for i in range(3):
...     try:
...         f()
...     except Exception as e:
...         e.add_note(f'Happened in Iteration {i+1}')
...         excs.append(e)
...
>>> raise ExceptionGroup('We have some problems', excs)
  + Exception Group Traceback (most recent call last):
  |   File "<stdin>", line 1, in <module>
  |     raise ExceptionGroup('We have some problems', excs)
  | ExceptionGroup: We have some problems (3 sub-exceptions)
  +-+---------------- 1 ----------------
    | Traceback (most recent call last):
    |   File "<stdin>", line 3, in <module>
    |     f()
    |     ~^^
    |   File "<stdin>", line 2, in f
    |     raise OSError('operation failed')
    | OSError: operation failed
    | Happened in Iteration 1
    +---------------- 2 ----------------
    | Traceback (most recent call last):
    |   File "<stdin>", line 3, in <module>
    |     f()
    |     ~^^
    |   File "<stdin>", line 2, in f
    |     raise OSError('operation failed')
    | OSError: operation failed
    | Happened in Iteration 2
    +---------------- 3 ----------------
    | Traceback (most recent call last):
    |   File "<stdin>", line 3, in <module>
    |     f()
    |     ~^^
    |   File "<stdin>", line 2, in f
    |     raise OSError('operation failed')
    | OSError: operation failed
    | Happened in Iteration 3
    +------------------------------------
>>>

1 . 6 Code Samples

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.6 Code Samples

The code samples in this book are written in pseudocode. These should be easy enough to read for anyone who has any programming experience in any of the most common programming languages of the last 40 years. To get an idea of what the pseudocode in this book looks like, here is a function that computes the average of an array, $ \ensuremath{\ensuremath{\mathit{a}}}$:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{average}(\en...
...it{s}}/\mathrm{length}(\ensuremath{\mathit{a}})}\\
\end{flushleft}\end{leftbar}
As this code illustrates, assigning to a variable is done using the $ \gets$ notation. We use the convention that the length of an array, $ \ensuremath{\ensuremath{\mathit{a}}}$, is denoted by $ \ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}$ and array indices start at zero, so that $ \ensuremath{0,1,2,\ldots,\mathrm{length}(\ensuremath{\mathit{a}})-1}$ are the valid indices for $ \ensuremath{\ensuremath{\mathit{a}}}$. To shorten code, and sometimes make it easier to read, our pseudocode allows for (sub)array assignments. The following two functions are equivalent:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{left\_shift\...
...uremath{\mathit{a}})-1}] \gets \ensuremath{nil}}\\
\end{flushleft}\end{leftbar}
The following code sets all the values in an array to zero:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{zero}(\ensur...
...suremath{\mathit{a}})-1}]} \gets \ensuremath{0}}\\
\end{flushleft}\end{leftbar}
When analyzing the running time of code like this, we have to be careful; statements like $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{0,1,\ldots,\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})-1}]} \gets \ensuremath{1}}$ or $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{1,2,\ldots,\ensuremath{\mathrm...
...athit{a}}[\ensuremath{0,1,\ldots,\mathrm{length}(\ensuremath{\mathit{a}})-2}]}}$ do not run in constant time. They run in $ O(\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}})$ time.

We take similar shortcuts with variable assignments, so that the code $ \ensuremath{\ensuremath{\mathit{x}},\ensuremath{y}\gets \ensuremath{0,1}}$ sets $ \ensuremath{\ensuremath{\mathit{x}}}$ to zero and $ \ensuremath{\ensuremath{\mathit{y}}}$ to 1 and the code $ \ensuremath{\ensuremath{\mathit{x}},\ensuremath{y} \gets \ensuremath{\ensuremath{\mathit{y}},x}}$ swaps the values of the variables $ \ensuremath{\ensuremath{\mathit{x}}}$ and $ \ensuremath{\ensuremath{\mathit{y}}}$.

Our pseudocode uses a few operators that may be unfamiliar. As is standard in mathematics, (normal) division is denoted by the $ /$ operator. In many cases, we want to do integer division instead, in which case we use the $ \ensuremath{\bdiv }$ operator, so that $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}\bdiv \ensuremath{\mathit{b}}}} = \lfloor a/b\rfloor$ is the integer part of $ a/b$. So, for example, $ 3/2=1.5$ but $ \ensuremath{\ensuremath{3\bdiv 2}} = 1$. Occasionally, we also use the $ \bmod$ operator to obtain the remainder from integer division, but this will be defined when it is used. Later in the book, we may use some bitwise operators including left-shift ( $ \ensuremath{\ll}$), right shift ( $ \ensuremath{\gg}$), bitwise and ($ \wedge $), and bitwise exclusive-or ( $ \ensuremath{\oplus}$).

The pseudocode samples in this book are machine translations of Python code that can be downloaded from the book's website.1.2 If you ever encounter an ambiguity in the pseudocode that you can't resolve yourself, then you can always refer to the corresponding Python code. If you don't read Python, the code is also available in Java and C++. If you can't decipher the pseudocode, or read Python, C++, or Java, then you may not be ready for this book.



Footnotes

... website.1.2
http://opendatastructures.org
opendatastructures.org

3 . 1 SLList: A Singly-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.1 SLList: A Singly-Linked List

An SLList (singly-linked list) is a sequence of Nodes. Each node $ \ensuremath{\ensuremath{\mathit{u}}}$ stores a data value $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{x}}}$ and a reference $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{next}}}$ to the next node in the sequence. For the last node $ \ensuremath{\ensuremath{\mathit{w}}}$ in the sequence, $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{next}}}} = \ensuremath{\ensuremath{\ensuremath{\mathit{nil}}}}$

For efficiency, an SLList uses variables $ \ensuremath{\ensuremath{\mathit{head}}}$ and $ \ensuremath{\ensuremath{\mathit{tail}}}$ to keep track of the first and last node in the sequence, as well as an integer $ \ensuremath{\ensuremath{\mathit{n}}}$ to keep track of the length of the sequence:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{initialize}(...
...nsuremath{\mathit{tail}} \gets \ensuremath{nil}}\\
\end{flushleft}\end{leftbar}
A sequence of Stack and Queue operations on an SLList is illustrated in Figure 3.1.

Figure 3.1: A sequence of Queue ( $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}()}$) and Stack ( $ \ensuremath{\mathrm{push}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{pop}()}$) operations on an SLList.
\includegraphics[width=\textwidth ]{figs-python/sllist}

An SLList can efficiently implement the Stack operations $ \ensuremath{\mathrm{push}()}$ and $ \ensuremath{\mathrm{pop}()}$ by adding and removing elements at the head of the sequence. The $ \ensuremath{\mathrm{push}()}$ operation simply creates a new node $ \ensuremath{\ensuremath{\mathit{u}}}$ with data value $ \ensuremath{\ensuremath{\mathit{x}}}$, sets $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{next}}}$ to the old head of the list and makes $ \ensuremath{\ensuremath{\mathit{u}}}$ the new head of the list. Finally, it increments $ \ensuremath{\ensuremath{\mathit{n}}}$ since the size of the SLList has increased by one:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{push}(\ensur...
...bf{return}} \ensuremath{\ensuremath{\mathit{x}}}\\
\end{flushleft}\end{leftbar}

The $ \ensuremath{\mathrm{pop}()}$ operation, after checking that the SLList is not empty, removes the head by setting $ \ensuremath{\ensuremath{\ensuremath{\mathit{head}}\gets \ensuremath{\ensuremath{\mathit{head}}.next}}}$ and decrementing $ \ensuremath{\ensuremath{\mathit{n}}}$. A special case occurs when the last element is being removed, in which case $ \ensuremath{\ensuremath{\mathit{tail}}}$ is set to $ \ensuremath{\ensuremath{\mathit{nil}}}$:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{pop}()}\\
\...
...bf{return}} \ensuremath{\ensuremath{\mathit{x}}}\\
\end{flushleft}\end{leftbar}

Clearly, both the $ \ensuremath{\mathrm{push}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{pop}()}$ operations run in $ O(1)$ time.

3.1.1 Queue Operations

An SLList can also implement the FIFO queue operations $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}()}$ in constant time. Removals are done from the head of the list, and are identical to the $ \ensuremath{\mathrm{pop}()}$ operation:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}()}\\...
...ck} \textbf{return}} \ensuremath{\mathrm{pop}()}\\
\end{flushleft}\end{leftbar}

Additions, on the other hand, are done at the tail of the list. In most cases, this is done by setting $ \ensuremath{\ensuremath{\ensuremath{\mathit{tail}}.\ensuremath{\mathit{next}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}$, where $ \ensuremath{\ensuremath{\mathit{u}}}$ is the newly created node that contains $ \ensuremath{\ensuremath{\mathit{x}}}$. However, a special case occurs when $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}=0$, in which case $ \ensuremath{\ensuremath{\ensuremath{\mathit{tail}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{head}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{nil}}}}$. In this case, both $ \ensuremath{\ensuremath{\mathit{tail}}}$ and $ \ensuremath{\ensuremath{\mathit{head}}}$ are set to $ \ensuremath{\ensuremath{\mathit{u}}}$.


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
...return}} \ensuremath{\ensuremath{\mathit{true}}}\\
\end{flushleft}\end{leftbar}

Clearly, both $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}()}$ take constant time.

3.1.2 Summary

The following theorem summarizes the performance of an SLList:

Theorem 3..1   An SLList implements the Stack and (FIFO) Queue interfaces. The $ \ensuremath{\mathrm{push}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{pop}()}$, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}()}$ operations run in $ O(1)$ time per operation.

An SLList nearly implements the full set of Deque operations. The only missing operation is removing from the tail of an SLList. Removing from the tail of an SLList is difficult because it requires updating the value of $ \ensuremath{\ensuremath{\mathit{tail}}}$ so that it points to the node $ \ensuremath{\ensuremath{\mathit{w}}}$ that precedes $ \ensuremath{\ensuremath{\mathit{tail}}}$ in the SLList; this is the node $ \ensuremath{\ensuremath{\mathit{w}}}$ such that $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{next}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{tail}}}}$. Unfortunately, the only way to get to $ \ensuremath{\ensuremath{\mathit{w}}}$ is by traversing the SLList starting at $ \ensuremath{\ensuremath{\mathit{head}}}$ and taking $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-2$ steps.

opendatastructures.org

7 . Random Binary Search Trees

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.


7. Random Binary Search Trees

In this chapter, we present a binary search tree structure that uses randomization to achieve $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time for all operations.



Subsections

opendatastructures.org

10 . 2 MeldableHeap: A Randomized Meldable Heap

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


10.2 MeldableHeap: A Randomized Meldable Heap

In this section, we describe the MeldableHeap, a priority Queue implementation in which the underlying structure is also a heap-ordered binary tree. However, unlike a BinaryHeap in which the underlying binary tree is completely defined by the number of elements, there are no restrictions on the shape of the binary tree that underlies a MeldableHeap; anything goes.

The $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}()}$ operations in a MeldableHeap are implemented in terms of the $ \ensuremath{\mathrm{merge}(\ensuremath{\mathit{h_1}},\ensuremath{\mathit{h_2}})}$ operation. This operation takes two heap nodes $ \ensuremath{\ensuremath{\mathit{h_1}}}$ and $ \ensuremath{\ensuremath{\mathit{h_2}}}$ and merges them, returning a heap node that is the root of a heap that contains all elements in the subtree rooted at $ \ensuremath{\ensuremath{\mathit{h_1}}}$ and all elements in the subtree rooted at $ \ensuremath{\ensuremath{\mathit{h_2}}}$.

The nice thing about a $ \ensuremath{\mathrm{merge}(\ensuremath{\mathit{h_1}},\ensuremath{\mathit{h_2}})}$ operation is that it can be defined recursively. See Figure 10.4. If either $ \ensuremath{\ensuremath{\mathit{h_1}}}$ or $ \ensuremath{\ensuremath{\mathit{h_2}}}$ is $ \ensuremath{\ensuremath{\mathit{nil}}}$, then we are merging with an empty set, so we return $ \ensuremath{\ensuremath{\mathit{h_2}}}$ or $ \ensuremath{\ensuremath{\mathit{h_1}}}$, respectively. Otherwise, assume $ \ensuremath{\ensuremath{\ensuremath{\mathit{h_1}}.\ensuremath{\mathit{x}}}} \le \ensuremath{\ensuremath{\ensuremath{\mathit{h_2}}.\ensuremath{\mathit{x}}}}$ since, if $ \ensuremath{\ensuremath{\ensuremath{\mathit{h_1}}.\ensuremath{\mathit{x}}}} > \ensuremath{\ensuremath{\ensuremath{\mathit{h_2}}.\ensuremath{\mathit{x}}}}$, then we can reverse the roles of $ \ensuremath{\ensuremath{\mathit{h_1}}}$ and $ \ensuremath{\ensuremath{\mathit{h_2}}}$. Then we know that the root of the merged heap will contain $ \ensuremath{\ensuremath{\mathit{h_1}}.\ensuremath{\mathit{x}}}$, and we can recursively merge $ \ensuremath{\ensuremath{\mathit{h_2}}}$ with $ \ensuremath{\ensuremath{\mathit{h_1}}.\ensuremath{\mathit{left}}}$ or $ \ensuremath{\ensuremath{\mathit{h_1}}.\ensuremath{\mathit{right}}}$, as we wish. This is where randomization comes in, and we toss a coin to decide whether to merge $ \ensuremath{\ensuremath{\mathit{h_2}}}$ with $ \ensuremath{\ensuremath{\mathit{h_1}}.\ensuremath{\mathit{left}}}$ or $ \ensuremath{\ensuremath{\mathit{h_1}}.\ensuremath{\mathit{right}}}$:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{merge}(\ensu...
...{return}} \ensuremath{\ensuremath{\mathit{h_1}}}\\
\end{flushleft}\end{leftbar}

Figure 10.4: Merging $ \ensuremath{\ensuremath{\mathit{h_1}}}$ and $ \ensuremath{\ensuremath{\mathit{h_2}}}$ is done by merging $ \ensuremath{\ensuremath{\mathit{h_2}}}$ with one of $ \ensuremath{\ensuremath{\mathit{h_1}}.\ensuremath{\mathit{left}}}$ or $ \ensuremath{\ensuremath{\mathit{h_1}}.\ensuremath{\mathit{right}}}$.
\includegraphics[width=\textwidth ]{figs-python/meldable-merge}

In the next section, we show that $ \ensuremath{\mathrm{merge}(\ensuremath{\mathit{h_1}},\ensuremath{\mathit{h_2}})}$ runs in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time, where $ \ensuremath{\ensuremath{\mathit{n}}}$ is the total number of elements in $ \ensuremath{\ensuremath{\mathit{h_1}}}$ and $ \ensuremath{\ensuremath{\mathit{h_2}}}$.

With access to a $ \ensuremath{\mathrm{merge}(\ensuremath{\mathit{h_1}},\ensuremath{\mathit{h_2}})}$ operation, the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation is easy. We create a new node $ \ensuremath{\ensuremath{\mathit{u}}}$ containing $ \ensuremath{\ensuremath{\mathit{x}}}$ and then merge $ \ensuremath{\ensuremath{\mathit{u}}}$ with the root of our heap:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
...return}} \ensuremath{\ensuremath{\mathit{true}}}\\
\end{flushleft}\end{leftbar}
This takes $ O(\log (\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1)) = O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time.

The $ \ensuremath{\mathrm{remove}()}$ operation is similarly easy. The node we want to remove is the root, so we just merge its two children and make the result the root:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}()}\\...
...bf{return}} \ensuremath{\ensuremath{\mathit{x}}}\\
\end{flushleft}\end{leftbar}
Again, this takes $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time.

Additionally, a MeldableHeap can implement many other operations in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time, including:

Each of these operations can be implemented using a constant number of $ \ensuremath{\mathrm{merge}(\ensuremath{\mathit{h_1}},\ensuremath{\mathit{h_2}})}$ operations that each take $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time.

10.2.1 Analysis of $ \ensuremath{\mathrm{merge}(\ensuremath{\mathit{h_1}},\ensuremath{\mathit{h_2}})}$

The analysis of $ \ensuremath{\mathrm{merge}(\ensuremath{\mathit{h_1}},\ensuremath{\mathit{h_2}})}$ is based on the analysis of a random walk in a binary tree. A random walk in a binary tree starts at the root of the tree. At each step in the random walk, a coin is tossed and, depending on the result of this coin toss, the walk proceeds to the left or to the right child of the current node. The walk ends when it falls off the tree (the current node becomes $ \ensuremath{\ensuremath{\mathit{nil}}}$).

The following lemma is somewhat remarkable because it does not depend at all on the shape of the binary tree:

Lemma 10..1   The expected length of a random walk in a binary tree with $ \ensuremath{\ensuremath{\mathit{n}}}$ nodes is at most $ \log \ensuremath{(\ensuremath{\mathit{n}}+1)}$.

Proof. The proof is by induction on $ \ensuremath{\ensuremath{\mathit{n}}}$. In the base case, $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}=0$ and the walk has length $ 0=\log (\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1)$. Suppose now that the result is true for all non-negative integers $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}'< \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$.

Let $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_1$ denote the size of the root's left subtree, so that $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_2=\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_1-1$ is the size of the root's right subtree. Starting at the root, the walk takes one step and then continues in a subtree of size $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_1$ or $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_2$. By our inductive hypothesis, the expected length of the walk is then

$\displaystyle \mathrm{E}[W] = 1 + \frac{1}{2}\log (\ensuremath{\ensuremath{\ens...
...{1}{2}\log (\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_2+1) \enspace ,
$

since each of $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_1$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_2$ are less than $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$. Since $ \log$ is a concave function, $ \mathrm{E}[W]$ is maximized when $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_1=\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_2=(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1)/2$. Therefore, the expected number of steps taken by the random walk is

$\displaystyle \mathrm{E}[W]$ $\displaystyle = 1 + \frac{1}{2}\log (\ensuremath{\ensuremath{\ensuremath{\mathi...
..._1+1) + \frac{1}{2}\log (\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_2+1)$    
  $\displaystyle \le 1 + \log ((\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1)/2+1)$    
  $\displaystyle = 1 + \log ((\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1)/2)$    
  $\displaystyle = \log (\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1) \enspace . \qedhere$    

$ \qedsymbol$

We make a quick digression to note that, for readers who know a little about information theory, the proof of Lemma 10.1 can be stated in terms of entropy.

Proof. [Information Theoretic Proof of Lemma 10.1] Let $ d_i$ denote the depth of the $ i$th external node and recall that a binary tree with $ \ensuremath{\ensuremath{\mathit{n}}}$ nodes has $ \ensuremath{\ensuremath{\mathit{n}}+1}$ external nodes. The probability of the random walk reaching the $ i$th external node is exactly $ p_i=1/2^{d_i}$, so the expected length of the random walk is given by

$\displaystyle H=\sum_{i=0}^{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}} ...
...\sum_{i=0}^{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}p_i\log({1/p_i})
$

The right hand side of this equation is easily recognizable as the entropy of a probability distribution over $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1$ elements. A basic fact about the entropy of a distribution over $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1$ elements is that it does not exceed $ \log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1)$, which proves the lemma. $ \qedsymbol$

With this result on random walks, we can now easily prove that the running time of the $ \ensuremath{\mathrm{merge}(\ensuremath{\mathit{h_1}},\ensuremath{\mathit{h_2}})}$ operation is $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$.

Lemma 10..2   If $ \ensuremath{\ensuremath{\mathit{h_1}}}$ and $ \ensuremath{\ensuremath{\mathit{h_2}}}$ are the roots of two heaps containing $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_1$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_2$ nodes, respectively, then the expected running time of $ \ensuremath{\mathrm{merge}(\ensuremath{\mathit{h_1}},\ensuremath{\mathit{h_2}})}$ is at most $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$, where $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_1+\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_2$.

Proof. Each step of the merge algorithm takes one step of a random walk, either in the heap rooted at $ \ensuremath{\ensuremath{\mathit{h_1}}}$ or the heap rooted at $ \ensuremath{\ensuremath{\mathit{h_2}}}$. The algorithm terminates when either of these two random walks fall out of its corresponding tree (when $ \ensuremath{\ensuremath{\ensuremath{\mathit{h_1}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{nil}}}}$ or $ \ensuremath{\ensuremath{\ensuremath{\mathit{h_2}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{nil}}}}$). Therefore, the expected number of steps performed by the merge algorithm is at most

$\displaystyle \log (\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_1+1) + \l...
...e 2\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} \enspace . \qedhere
$

$ \qedsymbol$

10.2.2 Summary

The following theorem summarizes the performance of a MeldableHeap:

Theorem 10..2   A MeldableHeap implements the (priority) Queue interface. A MeldableHeap supports the operations $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}()}$ in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time per operation.

opendatastructures.org

How the web works

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.

How the web works

How the web works provides a high-level description of what happens when you use a web browser to navigate to a web page, explaining the magic that goes on behind the scenes to deliver the relevant code to your computer for the browser to assemble into something you can look at.

This theory is not essential to writing web code in the short term, but before long, you'll really start to benefit from understanding what's happening in the background.

Note: This article does not cover how web browsers actually render code into web pages. That's covered in How browsers load websites.

Prerequisites: Basic familiarity with your computer operating system, web browsers, and web technologies.
Learning outcomes:
  • Clients and servers and their roles in the web.
  • DNS and how it works, at a high level.
  • The purpose of TCP/IP, HTTP, and packets.
  • HTTP syntax at a basic level.
  • Common HTTP response codes (e.g., 200, 301, 403, 404, and 500).
  • Basic components of a URL (protocol, domain, subdomain, path).

Clients and servers

Computers connected to the internet are called clients and servers. A simplified diagram of how they interact might look like this:

Two circles representing client and server. An arrow labeled request is going from client to server, and an arrow labeled responses is going from server to client

  • Clients are the typical web user's internet-connected devices (for example, your computer connected to your Wi-Fi, or your phone connected to your mobile network) and web-accessing software available on those devices (usually a web browser like Firefox or Chrome).
  • Servers are computers that store webpages, sites, or apps. When a client wants to access a webpage, a copy of the webpage code is downloaded from the server to the client machine, where it is rendered by the browser and displayed to the user.

The following embedded content from ScrimbaMDN learning partner provides further information on clients and servers, including a quiz and discussion.

The other parts of the toolbox

The client and server we've described above don't tell the whole story. There are many other parts involved, and we'll describe them below.

For now, let's imagine that the internet is a road. On one end of the road is the client, which is like your house. On the other end of the road is the server, which is like a shop you want to buy something from.

A black-and-white photo of a person crossing a road at a crosswalk

For data to get back and forth, we need the following things:

  • Your internet connection: Allows you to send and receive data on the internet. It's basically like the street between your house and the shop.

  • TCP/IP: Transmission Control Protocol and Internet Protocol (TCP/IP) are communication protocols that define how data should travel across the internet. This is like the transport mechanisms that let you place an order, go to the shop, and buy your goods. In our example, this is like a car or a bike (or however else you might travel along the road).

  • DNS: The Domain Name System (DNS) is like an address book for websites. When you type a web address in your browser, the browser looks at the DNS to find the website's IP address — the actual address the server is located at — before it can retrieve the website (see DNS explained below for more information). The browser needs to find out which server the website lives on, so it can send HTTP messages to the right place (see below). This is like looking up the address of the shop before you visit it.

  • HTTP: Hypertext Transfer Protocol (HTTP) is an application protocol that defines a language for clients and servers to speak to each other. This is like the language you use to order your goods. See HTTP basics below.

  • Files: A website is made up of many different files, which are like the different goods you buy from the shop. These files come in two main types:

    • Code: Websites are built primarily from HTML, CSS, and JavaScript — the different programming languages websites are written in, which the browser interprets and assembles into a web page to display to a user.
    • Assets: This is a collective term for all the other items that appear on a website — such as images, music, video, Word documents, and PDFs — that aren't code that the browser interprets.

    Note: You can find out how the browser assembles these files into a web page later in the course, in How browsers load websites.

So what happens, exactly?

When you type a web address (which is technically part of a URL) into your browser address bar, the following steps occur:

  1. The browser goes to the DNS server and finds the real address of the server that the website lives on.
  2. The browser sends an HTTP request message to the server, asking it to send a copy of the website to the client. This message, and all other data sent between the client and the server, is sent across your internet connection using TCP/IP.
  3. If the server approves the client's request, the server sends the client a "200 OK" message, which means "Of course you can look at that website! Here it is", and then starts sending the website's files to the browser as a series of small chunks called packets.
  4. The browser assembles the small chunks into a complete web page and displays it to you.

DNS explained

Real web addresses (URLs) aren't the nice, memorable strings you type into your address bar to find your favorite websites. They are special numbers that look like this: 192.0.2.172.

This is called an IP address, and it represents a unique location on the web. However, it's not very easy to remember, is it? That's why the Domain Name System was invented. This system uses special servers that match up a web address you type into your browser (like mozilla.org) to the website's real (IP) address. Large websites are commonly made available on multiple servers, so that they load efficiently for different users worldwide. As a result, the IP address may vary depending on where you are.

You can use a DNS lookup tool to find the IP addresses of a website. For example, go to the NsLookup.io DNS lookup tool, type in developer.mozilla.org, and press the button.

Packets explained

Earlier, we used the term "packets" to describe the format in which the data is transferred between the client and server. What do we mean here?

When data is sent across the web, it is sent in multiple small chunks called packets. Each packet contains:

  • A header, which includes details such as the server and client IP address, the packet number, the total number of packets in the transmission, and details of the protocols used in the transmission.
  • A payload, which contains the actual data sent in the packet.

There are multiple reasons why data is sent in small packets, but most significantly:

  • They are sometimes dropped or corrupted, and when this happens, it's quicker and easier for the client to request the missing packets rather than an entire file.
  • The packets can be routed along different paths, making the transmission as efficient as possible and reducing the possibility of slowing down the network — especially when many users are requesting the same resource simultaneously. The packets may arrive out of sequence, but the client can use the information in the packet headers to make sure they are assembled in the correct order.

HTTP basics

HTTP uses a simple language of verbs to perform actions such as making requests (see HTTP request methods). The HTTP GET method is the one normally used to make HTTP requests of the type described above. For example, a request for the MDN home page might look like this:

http
GET /en-US/ HTTP/2

Host: developer.mozilla.org

The response sent by the server might look something like this:

http
HTTP/2 200

date: Tue, 11 Feb 2025 11:13:30 GMT
expires: Tue, 11 Feb 2025 11:40:01 GMT
server: Google frontend
last-modified: Tue, 11 Feb 2025 00:49:32 GMT
ETag: "65f26b7f6463e2347f4e5a7a2adcee54"
content-length: 45227
content-type: text/html

<!doctype html> ... (the 45227 bytes of the requested web page HTML)

The full response is more complex than this, but we have omitted most of it for brevity. The main parts are as follows:

HTTP/2 200

The version of HTTP that the server is using to send the response, in this case HTTP/2, followed by a status code indicating whether the request was successful. 200 indicates success.

date, expires, etc.

HTTP headers containing additional information about the response (note that requests can have headers too), which provide extra information and/or modify its behavior.

<!doctype html>, etc.

The response body, which in this case contains the MDN homepage's HTML document.

Note: See the MDN HTTP reference for a lot more detail on HTTP, if you are curious. An overview of HTTP is a good place to start.

Other status codes

Above, we met the 200 status code, which indicates that the HTTP request was successful. There are many HTTP status codes with specific meanings and uses, but you will only commonly see a few:

301

The requested resource has been permanently moved to a new location, which is provided in the response. This is used for redirecting content when it's moved.

400

The server can't process the request. This usually happens when the request isn't in a format the server understands, or has errors in it.

403

The server will not give the client access to the requested resource. This usually happens when the server knows who the client is, but they don't have permission to access the requested page.

404

The server cannot find the requested resource. This status is commonly returned if the URL is wrong or if content is deleted without putting a redirect in place.

503

The request cannot be handled due to a problem with the server. This is common when servers are offline for maintenance, and it's expected to be temporary.

Components of a URL

Technically, web addresses that you type into the browser address bar form part of Uniform Resource Locators (URLs). URLs define the locations of unique resources on the internet.

A URL is a web address plus a protocol: for example, if you open a new tab in your browser, type in developer.mozilla.org into the address bar, and press Enter/Return, you will be redirected to a URL like the following one:

https://developer.mozilla.org/en-US/

The main parts of the URL are:

https

The protocol being used to send the request. In this case, we are using HTTPS, which is a secure version of HTTP that stops bad people from reading your data while it is being transported. On the modern web, pretty much every server uses HTTPS, so if you don't include it explicitly, the browser assumes that is what you are using and adds it for you.

developer.mozilla.org

The domain name of the URL, which represents the top-level location of the server you are connecting to. In this case, the web address you typed in is equal to the domain name, but this is not always the case — you could choose to type in a more complicated web address. Note that the developer part is a subdomain (distinct content area) of Mozilla's mozilla.org domain. There are other subdomains on Mozilla's site that host distinct content — see support.mozilla.org and bugzilla.mozilla.org, for example.

/en-US/

The path to the resource on the server that you are accessing. MDN keeps all its US English content in a folder called en-US, which is what this URL is pointing to.

If you have your browser set up to prefer English content by default, then this is the URL you will be redirected to when you type in developer.mozilla.org. If you have your browser set up to prefer a different language that MDN supports, such as French, you will be redirected to a different URL, such as https://developer.mozilla.org/fr/ instead. This isn't available to every website by default; the MDN developers have set MDN up like this to allow people to easily access the language they prefer.

Note: There are a lot more components that can appear in URLs. See What is a URL? for more details.

See also

Credit

Street photo: Street composing, by Kevin Digga.

Working with objects

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.

Working with objects

JavaScript is designed on an object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.

Objects in JavaScript, just as in many other programming languages, can be compared to objects in real life. In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object with properties. A cup has a color, a design, weight, a material it is made of, etc. In the same way, JavaScript objects can have properties, which define their characteristics.

In addition to objects that are predefined in the browser, you can define your own objects. This chapter describes how to use objects, properties, and methods, and how to create your own objects.

Creating new objects

You can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object by invoking that function with the new operator.

Using object initializers

Object initializers are also called object literals. "Object initializer" is consistent with the terminology used by C++.

The syntax for an object using an object initializer is:

js
const obj = {
  property1: value1, // property name may be an identifier
  2: value2, // or a number
  "property n": value3, // or a string
};

Each property name before the colon is either an identifier, a number literal, or a string literal, and each valueN is an expression whose value is assigned to the property name. The property name can also be an expression; computed keys need to be wrapped in square brackets. The object initializer reference contains a more detailed explanation of the syntax.

In this example, the newly created object is assigned to a variable obj — this is optional. If you do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that you may need to wrap the object literal in parentheses if the object appears where a statement is expected, so as not to have the literal be confused with a block statement.)

Object initializers are expressions, and each object initializer results in a new object being created whenever the statement in which it appears is executed. Identical object initializers create distinct objects that do not compare to each other as equal.

The following statement creates an object and assigns it to the variable x if and only if the expression cond is true:

js
let x;
if (cond) {
  x = { greeting: "hi there" };
}

The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.

js
const myHonda = {
  color: "red",
  wheels: 4,
  engine: { cylinders: 4, size: 2.2 },
};

Objects created with initializers are called plain objects, because they are instances of Object, but not any other object type. Some object types have special initializer syntaxes — for example, array initializers and regex literals.

Using a constructor function

Alternatively, you can create an object with these two steps:

  1. Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
  2. Create an instance of the object with new.

To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

js
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

Notice the use of this to assign values to the object's properties based on the values passed to the function.

Now you can create an object called myCar as follows:

js
const myCar = new Car("Eagle", "Talon TSi", 1993);

This statement creates myCar and assigns it the specified values for its properties. Then the value of myCar.make is the string "Eagle", myCar.model is the string "Talon TSi", myCar.year is the integer 1993, and so on. The order of arguments and parameters should be the same.

You can create any number of Car objects by calls to new. For example,

js
const randCar = new Car("Nissan", "300ZX", 1992);
const kenCar = new Car("Mazda", "Miata", 1990);

An object can have a property that is itself another object. For example, suppose you define an object called Person as follows:

js
function Person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
}

and then instantiate two new Person objects as follows:

js
const rand = new Person("Rand McKinnon", 33, "M");
const ken = new Person("Ken Jones", 39, "M");

Then, you can rewrite the definition of Car to include an owner property that takes a Person object, as follows:

js
function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
}

To instantiate the new objects, you then use the following:

js
const car1 = new Car("Eagle", "Talon TSi", 1993, rand);
const car2 = new Car("Nissan", "300ZX", 1992, ken);

Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:

js
car2.owner.name;

You can always add a property to a previously defined object. For example, the statement

js
car1.color = "black";

adds a property color to car1, and assigns it a value of "black". However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the Car object type.

You can also use the class syntax instead of the function syntax to define a constructor function. For more information, see the class guide.

Using the Object.create() method

Objects can also be created using the Object.create() method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function.

js
// Animal properties and method encapsulation
const animalProto = {
  type: "Invertebrates", // Default value of properties
  displayType() {
    // Method which will display the type of animal
    console.log(this.type);
  },
};

// Create a new animal type called `animal`
const animal = Object.create(animalProto);
animal.displayType(); // Logs: Invertebrates

// Create a new animal type called fish
const fish = Object.create(animalProto);
fish.type = "Fishes";
fish.displayType(); // Logs: Fishes

Objects and properties

A JavaScript object has properties associated with it. Object properties are basically the same as variables, except that they are associated with objects, not scopes. The properties of an object define the characteristics of the object.

For example, this example creates an object named myCar, with properties named make, model, and year, with their values set to "Ford", "Mustang", and 1969:

js
const myCar = {
  make: "Ford",
  model: "Mustang",
  year: 1969,
};

Like JavaScript variables, property names are case sensitive. Property names can only be strings or Symbols — all keys are converted to strings unless they are Symbols. Array indices are, in fact, properties with string keys that contain integers.

Accessing properties

You can access a property of an object by its property name. Property accessors come in two syntaxes: dot notation and bracket notation. For example, you could access the properties of the myCar object as follows:

js
// Dot notation
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;

// Bracket notation
myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;

An object property name can be any JavaScript string or symbol, including an empty string. However, you cannot use dot notation to access a property whose name is not a valid JavaScript identifier. For example, a property name that has a space or a hyphen, that starts with a number, or that is held inside a variable can only be accessed using the bracket notation. This notation is also very useful when property names are to be dynamically determined, i.e., not determinable until runtime. Examples are as follows:

js
const myObj = {};
const str = "myString";
const rand = Math.random();
const anotherObj = {};

// Create additional properties on myObj
myObj.type = "Dot syntax for a key named type";
myObj["date created"] = "This key has a space";
myObj[str] = "This key is in variable str";
myObj[rand] = "A random number is the key here";
myObj[anotherObj] = "This key is object anotherObj";
myObj[""] = "This key is an empty string";

console.log(myObj);
// {
//   type: 'Dot syntax for a key named type',
//   'date created': 'This key has a space',
//   myString: 'This key is in variable str',
//   '0.6398914448618778': 'A random number is the key here',
//   '[object Object]': 'This key is object anotherObj',
//   '': 'This key is an empty string'
// }
console.log(myObj.myString); // 'This key is in variable str'

In the above code, the key anotherObj is an object, which is neither a string nor a symbol. When it is added to the myObj, JavaScript calls the toString() method of anotherObj, and use the resulting string as the new key.

You can also access properties with a string value stored in a variable. The variable must be passed in bracket notation. In the example above, the variable str held "myString" and it is "myString" that is the property name. Therefore, myObj.str will return as undefined.

js
str = "myString";
myObj[str] = "This key is in variable str";

console.log(myObj.str); // undefined

console.log(myObj[str]); // 'This key is in variable str'
console.log(myObj.myString); // 'This key is in variable str'

This allows accessing any property as determined at runtime:

js
let propertyName = "make";
myCar[propertyName] = "Ford";

// access different properties by changing the contents of the variable
propertyName = "model";
myCar[propertyName] = "Mustang";

console.log(myCar); // { make: 'Ford', model: 'Mustang' }

However, beware of using square brackets to access properties whose names are given by external input. This may make your code susceptible to object injection attacks.

Nonexistent properties of an object have the value undefined (and not null).

js
myCar.nonexistentProperty; // undefined

Enumerating properties

There are three native ways to list/traverse object properties:

  • for...in loops. This method traverses all of the enumerable string properties of an object as well as its prototype chain.
  • Object.keys(). This method returns an array with only the enumerable own string property names ("keys") in the object myObj, but not those in the prototype chain.
  • Object.getOwnPropertyNames(). This method returns an array containing all the own string property names in the object myObj, regardless of if they are enumerable or not.

You can use the bracket notation with for...in to iterate over all the enumerable properties of an object. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function:

js
function showProps(obj, objName) {
  let result = "";
  for (const i in obj) {
    // Object.hasOwn() is used to exclude properties from the object's
    // prototype chain and only show "own properties"
    if (Object.hasOwn(obj, i)) {
      result += `${objName}.${i} = ${obj[i]}\n`;
    }
  }
  console.log(result);
}

The term "own property" refers to the properties of the object, but excluding those of the prototype chain. So, the function call showProps(myCar, 'myCar') would print the following:

myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969

The above is equivalent to:

js
function showProps(obj, objName) {
  let result = "";
  Object.keys(obj).forEach((i) => {
    result += `${objName}.${i} = ${obj[i]}\n`;
  });
  console.log(result);
}

There is no native way to list all inherited properties, including non-enumerable ones. However, this can be achieved with the following function:

js
function listAllProperties(myObj) {
  let objectToInspect = myObj;
  let result = [];

  while (objectToInspect !== null) {
    result = result.concat(Object.getOwnPropertyNames(objectToInspect));
    objectToInspect = Object.getPrototypeOf(objectToInspect);
  }

  return result;
}

For more information, see Enumerability and ownership of properties.

Deleting properties

You can remove a non-inherited property using the delete operator. The following code shows how to remove a property.

js
// Creates a new object, myObj, with two properties, a and b.
const myObj = { a: 5, b: 12 };

// Removes the a property, leaving myObj with only the b property.
delete myObj.a;
console.log("a" in myObj); // false

Inheritance

All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the prototype object of the constructor. See Inheritance and the prototype chain for more information.

Defining properties for all objects of one type

You can add a property to all objects created through a certain constructor using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type Car, and then reads the property's value from an instance car1.

js
Car.prototype.color = "red";
console.log(car1.color); // "red"

Defining methods

A method is a function associated with an object, or, put differently, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See also method definitions for more details. An example is:

js
objectName.methodName = functionName;

const myObj = {
  myMethod: function (params) {
    // do something
  },

  // this works too!
  myOtherMethod(params) {
    // do something else
  },
};

where objectName is an existing object, methodName is the name you are assigning to the method, and functionName is the name of the function.

You can then call the method in the context of the object as follows:

js
objectName.methodName(params);

Methods are typically defined on the prototype object of the constructor, so that all objects of the same type share the same method. For example, you can define a function that formats and displays the properties of the previously-defined Car objects.

js
Car.prototype.displayCar = function () {
  const result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
  console.log(result);
};

Notice the use of this to refer to the object to which the method belongs. Then you can call the displayCar method for each of the objects as follows:

js
car1.displayCar();
car2.displayCar();

Using this for object references

JavaScript has a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have 2 objects, manager and intern. Each object has its own name, age and job. In the function sayHi(), notice the use of this.name. When added to the 2 objects, the same function will print the message with the name of the respective object it's attached to.

js
const manager = {
  name: "Karina",
  age: 27,
  job: "Software Engineer",
};
const intern = {
  name: "Tyrone",
  age: 21,
  job: "Software Engineer Intern",
};

function sayHi() {
  console.log(`Hello, my name is ${this.name}`);
}

// Add sayHi function to both objects
manager.sayHi = sayHi;
intern.sayHi = sayHi;

manager.sayHi(); // Hello, my name is Karina
intern.sayHi(); // Hello, my name is Tyrone

this is a "hidden parameter" of a function call that's passed in by specifying the object before the function that was called. For example, in manager.sayHi(), this is the manager object, because manager comes before the function sayHi(). If you access the same function from another object, this will change as well. If you use other methods to call the function, like Function.prototype.call() or Reflect.apply(), you can explicitly pass the value of this as an argument.

Defining getters and setters

A getter is a function associated with a property that gets the value of a specific property. A setter is a function associated with a property that sets the value of a specific property. Together, they can indirectly represent the value of a property.

Getters and setters can be either

Within object initializers, getters and setters are defined like regular methods, but prefixed with the keywords get or set. The getter method must not expect a parameter, while the setter method expects exactly one parameter (the new value to set). For instance:

js
const myObj = {
  a: 7,
  get b() {
    return this.a + 1;
  },
  set c(x) {
    this.a = x / 2;
  },
};

console.log(myObj.a); // 7
console.log(myObj.b); // 8, returned from the get b() method
myObj.c = 50; // Calls the set c(x) method
console.log(myObj.a); // 25

The myObj object's properties are:

  • myObj.a — a number
  • myObj.b — a getter that returns myObj.a plus 1
  • myObj.c — a setter that sets the value of myObj.a to half of the value myObj.c is being set to

Getters and setters can also be added to an object at any time after creation using the Object.defineProperties() method. This method's first parameter is the object on which you want to define the getter or setter. The second parameter is an object whose property names are the getter or setter names, and whose property values are objects for defining the getter or setter functions. Here's an example that defines the same getter and setter used in the previous example:

js
const myObj = { a: 0 };

Object.defineProperties(myObj, {
  b: {
    get() {
      return this.a + 1;
    },
  },
  c: {
    set(x) {
      this.a = x / 2;
    },
  },
});

myObj.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(myObj.b); // Runs the getter, which yields a + 1 or 6

Which of the two forms to choose depends on your programming style and task at hand. If you can change the definition of the original object, you will probably define getters and setters through the original initializer. This form is more compact and natural. However, if you need to add getters and setters later — maybe because you did not write the particular object — then the second form is the only possible form. The second form better represents the dynamic nature of JavaScript, but it can make the code hard to read and understand.

Comparing objects

In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

js
// Two variables, two distinct objects with the same properties
const fruit = { name: "apple" };
const anotherFruit = { name: "apple" };

fruit == anotherFruit; // return false
fruit === anotherFruit; // return false
js
// Two variables, a single object
const fruit = { name: "apple" };
const anotherFruit = fruit; // Assign fruit object reference to anotherFruit

// Here fruit and anotherFruit are pointing to same object
fruit == anotherFruit; // return true
fruit === anotherFruit; // return true

fruit.name = "grape";
console.log(anotherFruit); // { name: "grape" }; not { name: "apple" }

For more information about comparison operators, see equality operators.

See also

11.1. Introduction #

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.

11.1. Introduction #

Suppose we have a table similar to this:

CREATE TABLE test1 (
    id integer,
    content varchar
);

and the application issues many queries of the form:

SELECT content FROM test1 WHERE id = constant;

With no advance preparation, the system would have to scan the entire test1 table, row by row, to find all matching entries. If there are many rows in test1 and only a few rows (perhaps zero or one) that would be returned by such a query, this is clearly an inefficient method. But if the system has been instructed to maintain an index on the id column, it can use a more efficient method for locating matching rows. For instance, it might only have to walk a few levels deep into a search tree.

A similar approach is used in most non-fiction books: terms and concepts that are frequently looked up by readers are collected in an alphabetic index at the end of the book. The interested reader can scan the index relatively quickly and flip to the appropriate page(s), rather than having to read the entire book to find the material of interest. Just as it is the task of the author to anticipate the items that readers are likely to look up, it is the task of the database programmer to foresee which indexes will be useful.

The following command can be used to create an index on the id column, as discussed:

CREATE INDEX test1_id_index ON test1 (id);

The name test1_id_index can be chosen freely, but you should pick something that enables you to remember later what the index was for.

To remove an index, use the DROP INDEX command. Indexes can be added to and removed from tables at any time.

Once an index is created, no further intervention is required: the system will update the index when the table is modified, and it will use the index in queries when it thinks doing so would be more efficient than a sequential table scan. But you might have to run the ANALYZE command regularly to update statistics to allow the query planner to make educated decisions. See Chapter 14 for information about how to find out whether an index is used and when and why the planner might choose not to use an index.

Indexes can also benefit UPDATE and DELETE commands with search conditions. Indexes can moreover be used in join searches. Thus, an index defined on a column that is part of a join condition can also significantly speed up queries with joins.

In general, PostgreSQL indexes can be used to optimize queries that contain one or more WHERE or JOIN clauses of the form

indexed-column indexable-operator comparison-value

Here, the indexed-column is whatever column or expression the index has been defined on. The indexable-operator is an operator that is a member of the index's operator class for the indexed column. (More details about that appear below.) And the comparison-value can be any expression that is not volatile and does not reference the index's table.

In some cases the query planner can extract an indexable clause of this form from another SQL construct. A simple example is that if the original clause was

comparison-value operator indexed-column

then it can be flipped around into indexable form if the original operator has a commutator operator that is a member of the index's operator class.

Creating an index on a large table can take a long time. By default, PostgreSQL allows reads (SELECT statements) to occur on the table in parallel with index creation, but writes (INSERT, UPDATE, DELETE) are blocked until the index build is finished. In production environments this is often unacceptable. It is possible to allow writes to occur in parallel with index creation, but there are several caveats to be aware of — for more information see Building Indexes Concurrently.

After an index is created, the system has to keep it synchronized with the table. This adds overhead to data manipulation operations. Indexes can also prevent the creation of heap-only tuples. Therefore indexes that are seldom or never used in queries should be removed.

22.3. Single Variable Calculus Open the notebook in SageMaker Studio Lab

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

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

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

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

22.3. Single Variable Calculus
Open the notebook in SageMaker Studio Lab

In Section 2.4, we saw the basic elements of differential calculus. This section takes a deeper dive into the fundamentals of calculus and how we can understand and apply it in the context of machine learning.

22.3.1. Differential Calculus

Differential calculus is fundamentally the study of how functions behave under small changes. To see why this is so core to deep learning, let’s consider an example.

Suppose that we have a deep neural network where the weights are, for convenience, concatenated into a single vector \(\mathbf{w} = (w_1, \ldots, w_n)\). Given a training dataset, we consider the loss of our neural network on this dataset, which we will write as \(\mathcal{L}(\mathbf{w})\).

This function is extraordinarily complex, encoding the performance of all possible models of the given architecture on this dataset, so it is nearly impossible to tell what set of weights \(\mathbf{w}\) will minimize the loss. Thus, in practice, we often start by initializing our weights randomly, and then iteratively take small steps in the direction which makes the loss decrease as rapidly as possible.

The question then becomes something that on the surface is no easier: how do we find the direction which makes the weights decrease as quickly as possible? To dig into this, let’s first examine the case with only a single weight: \(L(\mathbf{w}) = L(x)\) for a single real value \(x\).

Let’s take \(x\) and try to understand what happens when we change it by a small amount to \(x + \epsilon\). If you wish to be concrete, think a number like \(\epsilon = 0.0000001\). To help us visualize what happens, let’s graph an example function, \(f(x) = \sin(x^x)\), over the \([0, 3]\).

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

torch.pi = torch.acos(torch.zeros(1)).item() * 2  # Define pi in torch

# Plot a function in a normal range
x_big = torch.arange(0.01, 3.01, 0.01)
ys = torch.sin(x_big**x_big)
d2l.plot(x_big, ys, 'x', 'f(x)')
../_images/output_single-variable-calculus_47f3dd_3_0.svg

At this large scale, the function’s behavior is not simple. However, if we reduce our range to something smaller like \([1.75,2.25]\), we see that the graph becomes much simpler.

# Plot a the same function in a tiny range
x_med = torch.arange(1.75, 2.25, 0.001)
ys = torch.sin(x_med**x_med)
d2l.plot(x_med, ys, 'x', 'f(x)')
../_images/output_single-variable-calculus_47f3dd_15_0.svg

Taking this to an extreme, if we zoom into a tiny segment, the behavior becomes far simpler: it is just a straight line.

# Plot a the same function in a tiny range
x_small = torch.arange(2.0, 2.01, 0.0001)
ys = torch.sin(x_small**x_small)
d2l.plot(x_small, ys, 'x', 'f(x)')
../_images/output_single-variable-calculus_47f3dd_27_0.svg

This is the key observation of single variable calculus: the behavior of familiar functions can be modeled by a line in a small enough range. This means that for most functions, it is reasonable to expect that as we shift the \(x\) value of the function by a little bit, the output \(f(x)\) will also be shifted by a little bit. The only question we need to answer is, “How large is the change in the output compared to the change in the input? Is it half as large? Twice as large?”

Thus, we can consider the ratio of the change in the output of a function for a small change in the input of the function. We can write this formally as

(22.3.1)\[\frac{L(x+\epsilon) - L(x)}{(x+\epsilon) - x} = \frac{L(x+\epsilon) - L(x)}{\epsilon}.\]

This is already enough to start to play around with in code. For instance, suppose that we know that \(L(x) = x^{2} + 1701(x-4)^3\), then we can see how large this value is at the point \(x = 4\) as follows.

# Define our function
def L(x):
    return x**2 + 1701*(x-4)**3

# Print the difference divided by epsilon for several epsilon
for epsilon in [0.1, 0.001, 0.0001, 0.00001]:
    print(f'epsilon = {epsilon:.5f} -> {(L(4+epsilon) - L(4)) / epsilon:.5f}')
epsilon = 0.10000 -> 25.11000
epsilon = 0.00100 -> 8.00270
epsilon = 0.00010 -> 8.00012
epsilon = 0.00001 -> 8.00001

Now, if we are observant, we will notice that the output of this number is suspiciously close to \(8\). Indeed, if we decrease \(\epsilon\), we will see value becomes progressively closer to \(8\). Thus we may conclude, correctly, that the value we seek (the degree a change in the input changes the output) should be \(8\) at the point \(x=4\). The way that a mathematician encodes this fact is

(22.3.2)\[\lim_{\epsilon \rightarrow 0}\frac{L(4+\epsilon) - L(4)}{\epsilon} = 8.\]

As a bit of a historical digression: in the first few decades of neural network research, scientists used this algorithm (the method of finite differences) to evaluate how a loss function changed under small perturbation: just change the weights and see how the loss changed. This is computationally inefficient, requiring two evaluations of the loss function to see how a single change of one variable influenced the loss. If we tried to do this with even a paltry few thousand parameters, it would require several thousand evaluations of the network over the entire dataset! It was not solved until 1986 that the backpropagation algorithm introduced in Rumelhart et al. (1988) provided a way to calculate how any change of the weights together would change the loss in the same computation time as a single prediction of the network over the dataset.

Back in our example, this value \(8\) is different for different values of \(x\), so it makes sense to define it as a function of \(x\). More formally, this value dependent rate of change is referred to as the derivative which is written as

(22.3.3)\[\frac{df}{dx}(x) = \lim_{\epsilon \rightarrow 0}\frac{f(x+\epsilon) - f(x)}{\epsilon}.\]

Different texts will use different notations for the derivative. For instance, all of the below notations indicate the same thing:

(22.3.4)\[\frac{df}{dx} = \frac{d}{dx}f = f' = \nabla_xf = D_xf = f_x.\]

Most authors will pick a single notation and stick with it, however even that is not guaranteed. It is best to be familiar with all of these. We will use the notation \(\frac{df}{dx}\) throughout this text, unless we want to take the derivative of a complex expression, in which case we will use \(\frac{d}{dx}f\) to write expressions like

(22.3.5)\[\frac{d}{dx}\left[x^4+\cos\left(\frac{x^2+1}{2x-1}\right)\right].\]

Oftentimes, it is intuitively useful to unravel the definition of derivative (22.3.3) again to see how a function changes when we make a small change of \(x\):

(22.3.6)\[\begin{split}\begin{aligned} \frac{df}{dx}(x) = \lim_{\epsilon \rightarrow 0}\frac{f(x+\epsilon) - f(x)}{\epsilon} & \implies \frac{df}{dx}(x) \approx \frac{f(x+\epsilon) - f(x)}{\epsilon} \\ & \implies \epsilon \frac{df}{dx}(x) \approx f(x+\epsilon) - f(x) \\ & \implies f(x+\epsilon) \approx f(x) + \epsilon \frac{df}{dx}(x). \end{aligned}\end{split}\]

The last equation is worth explicitly calling out. It tells us that if you take any function and change the input by a small amount, the output would change by that small amount scaled by the derivative.

In this way, we can understand the derivative as the scaling factor that tells us how large of change we get in the output from a change in the input.

22.3.2. Rules of Calculus

We now turn to the task of understanding how to compute the derivative of an explicit function. A full formal treatment of calculus would derive everything from first principles. We will not indulge in this temptation here, but rather provide an understanding of the common rules encountered.

22.3.2.1. Common Derivatives

As was seen in Section 2.4, when computing derivatives one can oftentimes use a series of rules to reduce the computation to a few core functions. We repeat them here for ease of reference.

  • Derivative of constants. \(\frac{d}{dx}c = 0\).

  • Derivative of linear functions. \(\frac{d}{dx}(ax) = a\).

  • Power rule. \(\frac{d}{dx}x^n = nx^{n-1}\).

  • Derivative of exponentials. \(\frac{d}{dx}e^x = e^x\).

  • Derivative of the logarithm. \(\frac{d}{dx}\log(x) = \frac{1}{x}\).

22.3.2.2. Derivative Rules

If every derivative needed to be separately computed and stored in a table, differential calculus would be near impossible. It is a gift of mathematics that we can generalize the above derivatives and compute more complex derivatives like finding the derivative of \(f(x) = \log\left(1+(x-1)^{10}\right)\). As was mentioned in Section 2.4, the key to doing so is to codify what happens when we take functions and combine them in various ways, most importantly: sums, products, and compositions.

  • Sum rule. \(\frac{d}{dx}\left(g(x) + h(x)\right) = \frac{dg}{dx}(x) + \frac{dh}{dx}(x)\).

  • Product rule. \(\frac{d}{dx}\left(g(x)\cdot h(x)\right) = g(x)\frac{dh}{dx}(x) + \frac{dg}{dx}(x)h(x)\).

  • Chain rule. \(\frac{d}{dx}g(h(x)) = \frac{dg}{dh}(h(x))\cdot \frac{dh}{dx}(x)\).

Let’s see how we may use (22.3.6) to understand these rules. For the sum rule, consider following chain of reasoning:

(22.3.7)\[\begin{split}\begin{aligned} f(x+\epsilon) & = g(x+\epsilon) + h(x+\epsilon) \\ & \approx g(x) + \epsilon \frac{dg}{dx}(x) + h(x) + \epsilon \frac{dh}{dx}(x) \\ & = g(x) + h(x) + \epsilon\left(\frac{dg}{dx}(x) + \frac{dh}{dx}(x)\right) \\ & = f(x) + \epsilon\left(\frac{dg}{dx}(x) + \frac{dh}{dx}(x)\right). \end{aligned}\end{split}\]

By comparing this result with the fact that \(f(x+\epsilon) \approx f(x) + \epsilon \frac{df}{dx}(x)\), we see that \(\frac{df}{dx}(x) = \frac{dg}{dx}(x) + \frac{dh}{dx}(x)\) as desired. The intuition here is: when we change the input \(x\), \(g\) and \(h\) jointly contribute to the change of the output by \(\frac{dg}{dx}(x)\) and \(\frac{dh}{dx}(x)\).

The product is more subtle, and will require a new observation about how to work with these expressions. We will begin as before using (22.3.6):

(22.3.8)\[\begin{split}\begin{aligned} f(x+\epsilon) & = g(x+\epsilon)\cdot h(x+\epsilon) \\ & \approx \left(g(x) + \epsilon \frac{dg}{dx}(x)\right)\cdot\left(h(x) + \epsilon \frac{dh}{dx}(x)\right) \\ & = g(x)\cdot h(x) + \epsilon\left(g(x)\frac{dh}{dx}(x) + \frac{dg}{dx}(x)h(x)\right) + \epsilon^2\frac{dg}{dx}(x)\frac{dh}{dx}(x) \\ & = f(x) + \epsilon\left(g(x)\frac{dh}{dx}(x) + \frac{dg}{dx}(x)h(x)\right) + \epsilon^2\frac{dg}{dx}(x)\frac{dh}{dx}(x). \\ \end{aligned}\end{split}\]

This resembles the computation done above, and indeed we see our answer (\(\frac{df}{dx}(x) = g(x)\frac{dh}{dx}(x) + \frac{dg}{dx}(x)h(x)\)) sitting next to \(\epsilon\), but there is the issue of that term of size \(\epsilon^{2}\). We will refer to this as a higher-order term, since the power of \(\epsilon^2\) is higher than the power of \(\epsilon^1\). We will see in a later section that we will sometimes want to keep track of these, however for now observe that if \(\epsilon = 0.0000001\), then \(\epsilon^{2}= 0.0000000000001\), which is vastly smaller. As we send \(\epsilon \rightarrow 0\), we may safely ignore the higher order terms. As a general convention in this appendix, we will use “\(\approx\)” to denote that the two terms are equal up to higher order terms. However, if we wish to be more formal we may examine the difference quotient

(22.3.9)\[\frac{f(x+\epsilon) - f(x)}{\epsilon} = g(x)\frac{dh}{dx}(x) + \frac{dg}{dx}(x)h(x) + \epsilon \frac{dg}{dx}(x)\frac{dh}{dx}(x),\]

and see that as we send \(\epsilon \rightarrow 0\), the right hand term goes to zero as well.

Finally, with the chain rule, we can again progress as before using (22.3.6) and see that

(22.3.10)\[\begin{split}\begin{aligned} f(x+\epsilon) & = g(h(x+\epsilon)) \\ & \approx g\left(h(x) + \epsilon \frac{dh}{dx}(x)\right) \\ & \approx g(h(x)) + \epsilon \frac{dh}{dx}(x) \frac{dg}{dh}(h(x))\\ & = f(x) + \epsilon \frac{dg}{dh}(h(x))\frac{dh}{dx}(x), \end{aligned}\end{split}\]

where in the second line we view the function \(g\) as having its input (\(h(x)\)) shifted by the tiny quantity \(\epsilon \frac{dh}{dx}(x)\).

These rule provide us with a flexible set of tools to compute essentially any expression desired. For instance,

(22.3.11)\[\begin{split}\begin{aligned} \frac{d}{dx}\left[\log\left(1+(x-1)^{10}\right)\right] & = \left(1+(x-1)^{10}\right)^{-1}\frac{d}{dx}\left[1+(x-1)^{10}\right]\\ & = \left(1+(x-1)^{10}\right)^{-1}\left(\frac{d}{dx}[1] + \frac{d}{dx}[(x-1)^{10}]\right) \\ & = \left(1+(x-1)^{10}\right)^{-1}\left(0 + 10(x-1)^9\frac{d}{dx}[x-1]\right) \\ & = 10\left(1+(x-1)^{10}\right)^{-1}(x-1)^9 \\ & = \frac{10(x-1)^9}{1+(x-1)^{10}}. \end{aligned}\end{split}\]

Where each line has used the following rules:

  1. The chain rule and derivative of logarithm.

  2. The sum rule.

  3. The derivative of constants, chain rule, and power rule.

  4. The sum rule, derivative of linear functions, derivative of constants.

Two things should be clear after doing this example:

  1. Any function we can write down using sums, products, constants, powers, exponentials, and logarithms can have its derivate computed mechanically by following these rules.

  2. Having a human follow these rules can be tedious and error prone!

Thankfully, these two facts together hint towards a way forward: this is a perfect candidate for mechanization! Indeed backpropagation, which we will revisit later in this section, is exactly that.

22.3.2.3. Linear Approximation

When working with derivatives, it is often useful to geometrically interpret the approximation used above. In particular, note that the equation

(22.3.12)\[f(x+\epsilon) \approx f(x) + \epsilon \frac{df}{dx}(x),\]

approximates the value of \(f\) by a line which passes through the point \((x, f(x))\) and has slope \(\frac{df}{dx}(x)\). In this way we say that the derivative gives a linear approximation to the function \(f\), as illustrated below:

# Compute sin
xs = torch.arange(-torch.pi, torch.pi, 0.01)
plots = [torch.sin(xs)]

# Compute some linear approximations. Use d(sin(x))/dx = cos(x)
for x0 in [-1.5, 0.0, 2.0]:
    plots.append(torch.sin(torch.tensor(x0)) + (xs - x0) *
                 torch.cos(torch.tensor(x0)))

d2l.plot(xs, plots, 'x', 'f(x)', ylim=[-1.5, 1.5])
../_images/output_single-variable-calculus_47f3dd_51_0.svg

22.3.2.4. Higher Order Derivatives

Let’s now do something that may on the surface seem strange. Take a function \(f\) and compute the derivative \(\frac{df}{dx}\). This gives us the rate of change of \(f\) at any point.

However, the derivative, \(\frac{df}{dx}\), can be viewed as a function itself, so nothing stops us from computing the derivative of \(\frac{df}{dx}\) to get \(\frac{d^2f}{dx^2} = \frac{df}{dx}\left(\frac{df}{dx}\right)\). We will call this the second derivative of \(f\). This function is the rate of change of the rate of change of \(f\), or in other words, how the rate of change is changing. We may apply the derivative any number of times to obtain what is called the \(n\)-th derivative. To keep the notation clean, we will denote the \(n\)-th derivative as

(22.3.13)\[f^{(n)}(x) = \frac{d^{n}f}{dx^{n}} = \left(\frac{d}{dx}\right)^{n} f.\]

Let’s try to understand why this is a useful notion. Below, we visualize \(f^{(2)}(x)\), \(f^{(1)}(x)\), and \(f(x)\).

First, consider the case that the second derivative \(f^{(2)}(x)\) is a positive constant. This means that the slope of the first derivative is positive. As a result, the first derivative \(f^{(1)}(x)\) may start out negative, becomes zero at a point, and then becomes positive in the end. This tells us the slope of our original function \(f\) and therefore, the function \(f\) itself decreases, flattens out, then increases. In other words, the function \(f\) curves up, and has a single minimum as is shown in Fig. 22.3.1.

../_images/posSecDer.svg

Fig. 22.3.1 If we assume the second derivative is a positive constant, then the fist derivative in increasing, which implies the function itself has a minimum.

Second, if the second derivative is a negative constant, that means that the first derivative is decreasing. This implies the first derivative may start out positive, becomes zero at a point, and then becomes negative. Hence, the function \(f\) itself increases, flattens out, then decreases. In other words, the function \(f\) curves down, and has a single maximum as is shown in Fig. 22.3.2.

../_images/negSecDer.svg

Fig. 22.3.2 If we assume the second derivative is a negative constant, then the fist derivative in decreasing, which implies the function itself has a maximum.

Third, if the second derivative is a always zero, then the first derivative will never change—it is constant! This means that \(f\) increases (or decreases) at a fixed rate, and \(f\) is itself a straight line as is shown in Fig. 22.3.3.

../_images/zeroSecDer.svg

Fig. 22.3.3 If we assume the second derivative is zero, then the fist derivative is constant, which implies the function itself is a straight line.

To summarize, the second derivative can be interpreted as describing the way that the function \(f\) curves. A positive second derivative leads to a upwards curve, while a negative second derivative means that \(f\) curves downwards, and a zero second derivative means that \(f\) does not curve at all.

Let’s take this one step further. Consider the function \(g(x) = ax^{2}+ bx + c\). We can then compute that

(22.3.14)\[\begin{split}\begin{aligned} \frac{dg}{dx}(x) & = 2ax + b \\ \frac{d^2g}{dx^2}(x) & = 2a. \end{aligned}\end{split}\]

If we have some original function \(f(x)\) in mind, we may compute the first two derivatives and find the values for \(a, b\), and \(c\) that make them match this computation. Similarly to the previous section where we saw that the first derivative gave the best approximation with a straight line, this construction provides the best approximation by a quadratic. Let’s visualize this for \(f(x) = \sin(x)\).

# Compute sin
xs = torch.arange(-torch.pi, torch.pi, 0.01)
plots = [torch.sin(xs)]

# Compute some quadratic approximations. Use d(sin(x)) / dx = cos(x)
for x0 in [-1.5, 0.0, 2.0]:
    plots.append(torch.sin(torch.tensor(x0)) + (xs - x0) *
                 torch.cos(torch.tensor(x0)) - (xs - x0)**2 *
                 torch.sin(torch.tensor(x0)) / 2)

d2l.plot(xs, plots, 'x', 'f(x)', ylim=[-1.5, 1.5])
../_images/output_single-variable-calculus_47f3dd_63_0.svg

We will extend this idea to the idea of a Taylor series in the next section.

22.3.2.5. Taylor Series

The Taylor series provides a method to approximate the function \(f(x)\) if we are given values for the first \(n\) derivatives at a point \(x_0\), i.e., \(\left\{ f(x_0), f^{(1)}(x_0), f^{(2)}(x_0), \ldots, f^{(n)}(x_0) \right\}\). The idea will be to find a degree \(n\) polynomial that matches all the given derivatives at \(x_0\).

We saw the case of \(n=2\) in the previous section and a little algebra shows this is

(22.3.15)\[f(x) \approx \frac{1}{2}\frac{d^2f}{dx^2}(x_0)(x-x_0)^{2}+ \frac{df}{dx}(x_0)(x-x_0) + f(x_0).\]

As we can see above, the denominator of \(2\) is there to cancel out the \(2\) we get when we take two derivatives of \(x^2\), while the other terms are all zero. Same logic applies for the first derivative and the value itself.

If we push the logic further to \(n=3\), we will conclude that

(22.3.16)\[f(x) \approx \frac{\frac{d^3f}{dx^3}(x_0)}{6}(x-x_0)^3 + \frac{\frac{d^2f}{dx^2}(x_0)}{2}(x-x_0)^{2}+ \frac{df}{dx}(x_0)(x-x_0) + f(x_0).\]

where the \(6 = 3 \times 2 = 3!\) comes from the constant we get in front if we take three derivatives of \(x^3\).

Furthermore, we can get a degree \(n\) polynomial by

(22.3.17)\[P_n(x) = \sum_{i = 0}^{n} \frac{f^{(i)}(x_0)}{i!}(x-x_0)^{i}.\]

where the notation

(22.3.18)\[f^{(n)}(x) = \frac{d^{n}f}{dx^{n}} = \left(\frac{d}{dx}\right)^{n} f.\]

Indeed, \(P_n(x)\) can be viewed as the best \(n\)-th degree polynomial approximation to our function \(f(x)\).

While we are not going to dive all the way into the error of the above approximations, it is worth mentioning the infinite limit. In this case, for well behaved functions (known as real analytic functions) like \(\cos(x)\) or \(e^{x}\), we can write out the infinite number of terms and approximate the exactly same function

(22.3.19)\[f(x) = \sum_{n = 0}^\infty \frac{f^{(n)}(x_0)}{n!}(x-x_0)^{n}.\]

Take \(f(x) = e^{x}\) as am example. Since \(e^{x}\) is its own derivative, we know that \(f^{(n)}(x) = e^{x}\). Therefore, \(e^{x}\) can be reconstructed by taking the Taylor series at \(x_0 = 0\), i.e.,

(22.3.20)\[e^{x} = \sum_{n = 0}^\infty \frac{x^{n}}{n!} = 1 + x + \frac{x^2}{2} + \frac{x^3}{6} + \cdots.\]

Let’s see how this works in code and observe how increasing the degree of the Taylor approximation brings us closer to the desired function \(e^x\).

# Compute the exponential function
xs = torch.arange(0, 3, 0.01)
ys = torch.exp(xs)

# Compute a few Taylor series approximations
P1 = 1 + xs
P2 = 1 + xs + xs**2 / 2
P5 = 1 + xs + xs**2 / 2 + xs**3 / 6 + xs**4 / 24 + xs**5 / 120

d2l.plot(xs, [ys, P1, P2, P5], 'x', 'f(x)', legend=[
    "Exponential", "Degree 1 Taylor Series", "Degree 2 Taylor Series",
    "Degree 5 Taylor Series"])
../_images/output_single-variable-calculus_47f3dd_75_0.svg

Taylor series have two primary applications:

  1. Theoretical applications: Often when we try to understand a too complex function, using Taylor series enables us to turn it into a polynomial that we can work with directly.

  2. Numerical applications: Some functions like \(e^{x}\) or \(\cos(x)\) are difficult for machines to compute. They can store tables of values at a fixed precision (and this is often done), but it still leaves open questions like “What is the 1000-th digit of \(\cos(1)\)?” Taylor series are often helpful to answer such questions.

22.3.3. Summary

  • Derivatives can be used to express how functions change when we change the input by a small amount.

  • Elementary derivatives can be combined using derivative rules to create arbitrarily complex derivatives.

  • Derivatives can be iterated to get second or higher order derivatives. Each increase in order provides more fine grained information on the behavior of the function.

  • Using information in the derivatives of a single data example, we can approximate well behaved functions by polynomials obtained from the Taylor series.

22.3.4. Exercises

  1. What is the derivative of \(x^3-4x+1\)?

  2. What is the derivative of \(\log(\frac{1}{x})\)?

  3. True or False: If \(f'(x) = 0\) then \(f\) has a maximum or minimum at \(x\)?

  4. Where is the minimum of \(f(x) = x\log(x)\) for \(x\ge0\) (where we assume that \(f\) takes the limiting value of \(0\) at \(f(0)\))?

12. Common pitfalls and recommended practices

Assigned source reading · The scikit-learn developers

Copyright (c) 2007–2026 The scikit-learn developers. All rights reserved.

Original source · BSD 3-Clause 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
BSD 3-Clause License

Copyright (c) 2007-2026 The scikit-learn developers.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

5.6. Dropout 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.

5.6. Dropout
Open the notebook in SageMaker Studio Lab

Let’s think briefly about what we expect from a good predictive model. We want it to peform well on unseen data. Classical generalization theory suggests that to close the gap between train and test performance, we should aim for a simple model. Simplicity can come in the form of a small number of dimensions. We explored this when discussing the monomial basis functions of linear models in Section 3.6. Additionally, as we saw when discussing weight decay (\(\ell_2\) regularization) in Section 3.7, the (inverse) norm of the parameters also represents a useful measure of simplicity. Another useful notion of simplicity is smoothness, i.e., that the function should not be sensitive to small changes to its inputs. For instance, when we classify images, we would expect that adding some random noise to the pixels should be mostly harmless.

Bishop (1995) formalized this idea when he proved that training with input noise is equivalent to Tikhonov regularization. This work drew a clear mathematical connection between the requirement that a function be smooth (and thus simple), and the requirement that it be resilient to perturbations in the input.

Then, Srivastava et al. (2014) developed a clever idea for how to apply Bishop’s idea to the internal layers of a network, too. Their idea, called dropout, involves injecting noise while computing each internal layer during forward propagation, and it has become a standard technique for training neural networks. The method is called dropout because we literally drop out some neurons during training. Throughout training, on each iteration, standard dropout consists of zeroing out some fraction of the nodes in each layer before calculating the subsequent layer.

To be clear, we are imposing our own narrative with the link to Bishop. The original paper on dropout offers intuition through a surprising analogy to sexual reproduction. The authors argue that neural network overfitting is characterized by a state in which each layer relies on a specific pattern of activations in the previous layer, calling this condition co-adaptation. Dropout, they claim, breaks up co-adaptation just as sexual reproduction is argued to break up co-adapted genes. While such an justification of this theory is certainly up for debate, the dropout technique itself has proved enduring, and various forms of dropout are implemented in most deep learning libraries.

The key challenge is how to inject this noise. One idea is to inject it in an unbiased manner so that the expected value of each layer—while fixing the others—equals the value it would have taken absent noise. In Bishop’s work, he added Gaussian noise to the inputs to a linear model. At each training iteration, he added noise sampled from a distribution with mean zero \(\epsilon \sim \mathcal{N}(0,\sigma^2)\) to the input \(\mathbf{x}\), yielding a perturbed point \(\mathbf{x}' = \mathbf{x} + \epsilon\). In expectation, \(E[\mathbf{x}'] = \mathbf{x}\).

In standard dropout regularization, one zeros out some fraction of the nodes in each layer and then debiases each layer by normalizing by the fraction of nodes that were retained (not dropped out). In other words, with dropout probability \(p\), each intermediate activation \(h\) is replaced by a random variable \(h'\) as follows:

(5.6.1)\[\begin{split}\begin{aligned} h' = \begin{cases} 0 & \textrm{ with probability } p \\ \frac{h}{1-p} & \textrm{ otherwise} \end{cases} \end{aligned}\end{split}\]

By design, the expectation remains unchanged, i.e., \(E[h'] = h\).

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

5.6.1. Dropout in Practice

Recall the MLP with a hidden layer and five hidden units from Fig. 5.1.1. When we apply dropout to a hidden layer, zeroing out each hidden unit with probability \(p\), the result can be viewed as a network containing only a subset of the original neurons. In Fig. 5.6.1, \(h_2\) and \(h_5\) are removed. Consequently, the calculation of the outputs no longer depends on \(h_2\) or \(h_5\) and their respective gradient also vanishes when performing backpropagation. In this way, the calculation of the output layer cannot be overly dependent on any one element of \(h_1, \ldots, h_5\).

../_images/dropout2.svg

Fig. 5.6.1 MLP before and after dropout.

Typically, we disable dropout at test time. Given a trained model and a new example, we do not drop out any nodes and thus do not need to normalize. However, there are some exceptions: some researchers use dropout at test time as a heuristic for estimating the uncertainty of neural network predictions: if the predictions agree across many different dropout outputs, then we might say that the network is more confident.

5.6.2. Implementation from Scratch

To implement the dropout function for a single layer, we must draw as many samples from a Bernoulli (binary) random variable as our layer has dimensions, where the random variable takes value \(1\) (keep) with probability \(1-p\) and \(0\) (drop) with probability \(p\). One easy way to implement this is to first draw samples from the uniform distribution \(U[0, 1]\). Then we can keep those nodes for which the corresponding sample is greater than \(p\), dropping the rest.

In the following code, we implement a dropout_layer function that drops out the elements in the tensor input X with probability dropout, rescaling the remainder as described above: dividing the survivors by 1.0-dropout.

def dropout_layer(X, dropout):
    assert 0 <= dropout <= 1
    if dropout == 1: return torch.zeros_like(X)
    mask = (torch.rand(X.shape) > dropout).float()
    return mask * X / (1.0 - dropout)

We can test out the dropout_layer function on a few examples. In the following lines of code, we pass our input X through the dropout operation, with probabilities 0, 0.5, and 1, respectively.

X = torch.arange(16, dtype = torch.float32).reshape((2, 8))
print('dropout_p = 0:', dropout_layer(X, 0))
print('dropout_p = 0.5:', dropout_layer(X, 0.5))
print('dropout_p = 1:', dropout_layer(X, 1))
dropout_p = 0: tensor([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11., 12., 13., 14., 15.]])
dropout_p = 0.5: tensor([[ 0.,  2.,  0.,  6.,  8.,  0.,  0.,  0.],
        [16., 18., 20., 22., 24., 26., 28., 30.]])
dropout_p = 1: tensor([[0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0.]])

5.6.2.1. Defining the Model

The model below applies dropout to the output of each hidden layer (following the activation function). We can set dropout probabilities for each layer separately. A common choice is to set a lower dropout probability closer to the input layer. We ensure that dropout is only active during training.

class DropoutMLPScratch(d2l.Classifier):
    def __init__(self, num_outputs, num_hiddens_1, num_hiddens_2,
                 dropout_1, dropout_2, lr):
        super().__init__()
        self.save_hyperparameters()
        self.lin1 = nn.LazyLinear(num_hiddens_1)
        self.lin2 = nn.LazyLinear(num_hiddens_2)
        self.lin3 = nn.LazyLinear(num_outputs)
        self.relu = nn.ReLU()

    def forward(self, X):
        H1 = self.relu(self.lin1(X.reshape((X.shape[0], -1))))
        if self.training:
            H1 = dropout_layer(H1, self.dropout_1)
        H2 = self.relu(self.lin2(H1))
        if self.training:
            H2 = dropout_layer(H2, self.dropout_2)
        return self.lin3(H2)

5.6.2.2. Training

The following is similar to the training of MLPs described previously.

hparams = {'num_outputs':10, 'num_hiddens_1':256, 'num_hiddens_2':256,
           'dropout_1':0.5, 'dropout_2':0.5, 'lr':0.1}
model = DropoutMLPScratch(**hparams)
data = d2l.FashionMNIST(batch_size=256)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)
../_images/output_dropout_1110bf_63_0.svg

5.6.3. Concise Implementation

With high-level APIs, all we need to do is add a Dropout layer after each fully connected layer, passing in the dropout probability as the only argument to its constructor. During training, the Dropout layer will randomly drop out outputs of the previous layer (or equivalently, the inputs to the subsequent layer) according to the specified dropout probability. When not in training mode, the Dropout layer simply passes the data through during testing.

class DropoutMLP(d2l.Classifier):
    def __init__(self, num_outputs, num_hiddens_1, num_hiddens_2,
                 dropout_1, dropout_2, lr):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(
            nn.Flatten(), nn.LazyLinear(num_hiddens_1), nn.ReLU(),
            nn.Dropout(dropout_1), nn.LazyLinear(num_hiddens_2), nn.ReLU(),
            nn.Dropout(dropout_2), nn.LazyLinear(num_outputs))

Next, we train the model.

model = DropoutMLP(**hparams)
trainer.fit(model, data)
../_images/output_dropout_1110bf_95_0.svg

5.6.4. Summary

Beyond controlling the number of dimensions and the size of the weight vector, dropout is yet another tool for avoiding overfitting. Often tools are used jointly. Note that dropout is used only during training: it replaces an activation \(h\) with a random variable with expected value \(h\).

5.6.5. Exercises

  1. What happens if you change the dropout probabilities for the first and second layers? In particular, what happens if you switch the ones for both layers? Design an experiment to answer these questions, describe your results quantitatively, and summarize the qualitative takeaways.

  2. Increase the number of epochs and compare the results obtained when using dropout with those when not using it.

  3. What is the variance of the activations in each hidden layer when dropout is and is not applied? Draw a plot to show how this quantity evolves over time for both models.

  4. Why is dropout not typically used at test time?

  5. Using the model in this section as an example, compare the effects of using dropout and weight decay. What happens when dropout and weight decay are used at the same time? Are the results additive? Are there diminished returns (or worse)? Do they cancel each other out?

  6. What happens if we apply dropout to the individual weights of the weight matrix rather than the activations?

  7. Invent another technique for injecting random noise at each layer that is different from the standard dropout technique. Can you develop a method that outperforms dropout on the Fashion-MNIST dataset (for a fixed architecture)?

8.8. Pairwise metrics, Affinities and Kernels

Assigned source reading · The scikit-learn developers

Copyright (c) 2007–2026 The scikit-learn developers. All rights reserved.

Original source · BSD 3-Clause 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
BSD 3-Clause License

Copyright (c) 2007-2026 The scikit-learn developers.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

8.8. Pairwise metrics, Affinities and Kernels

The sklearn.metrics.pairwise submodule implements utilities to evaluate pairwise distances or affinity of sets of samples.

This module contains both distance metrics and kernels. A brief summary is given on the two here.

Distance metrics are functions d(a, b) such that d(a, b) < d(a, c) if objects a and b are considered “more similar” than objects a and c. Two objects exactly alike would have a distance of zero. One of the most popular examples is Euclidean distance. To be a ‘true’ metric, it must obey the following four conditions:

1. d(a, b) >= 0, for all a and b
2. d(a, b) == 0, if and only if a = b, positive definiteness
3. d(a, b) == d(b, a), symmetry
4. d(a, c) <= d(a, b) + d(b, c), the triangle inequality

Kernels are measures of similarity, i.e. s(a, b) > s(a, c) if objects a and b are considered “more similar” than objects a and c. A kernel must also be positive semi-definite.

There are a number of ways to convert between a distance metric and a similarity measure, such as a kernel. Let D be the distance, and S be the kernel:

  1. S = np.exp(-D * gamma), where one heuristic for choosing

    gamma is 1 / num_features

  2. S = 1. / (D / np.max(D))

The distances between the row vectors of X and the row vectors of Y can be evaluated using pairwise_distances. If Y is omitted the pairwise distances of the row vectors of X are calculated. Similarly, pairwise.pairwise_kernels can be used to calculate the kernel between X and Y using different kernel functions. See the API reference for more details.

>>> import numpy as np
>>> from sklearn.metrics import pairwise_distances
>>> from sklearn.metrics.pairwise import pairwise_kernels
>>> X = np.array([[2, 3], [3, 5], [5, 8]])
>>> Y = np.array([[1, 0], [2, 1]])
>>> pairwise_distances(X, Y, metric='manhattan')
array([[ 4.,  2.],
       [ 7.,  5.],
       [12., 10.]])
>>> pairwise_distances(X, metric='manhattan')
array([[0., 3., 8.],
       [3., 0., 5.],
       [8., 5., 0.]])
>>> pairwise_kernels(X, Y, metric='linear')
array([[ 2.,  7.],
       [ 3., 11.],
       [ 5., 18.]])

8.8.1. Cosine similarity

cosine_similarity computes the L2-normalized dot product of vectors. That is, if \(x\) and \(y\) are row vectors, their cosine similarity \(k\) is defined as:

\[k(x, y) = \frac{x y^\top}{\|x\| \|y\|}\]

This is called cosine similarity, because Euclidean (L2) normalization projects the vectors onto the unit sphere, and their dot product is then the cosine of the angle between the points denoted by the vectors.

This kernel is a popular choice for computing the similarity of documents represented as tf-idf vectors. cosine_similarity accepts scipy.sparse matrices. (Note that the tf-idf functionality in sklearn.feature_extraction.text can produce normalized vectors, in which case cosine_similarity is equivalent to linear_kernel, only slower.)

References

8.8.2. Linear kernel

The function linear_kernel computes the linear kernel, that is, a special case of polynomial_kernel with degree=1 and coef0=0 (homogeneous). If x and y are column vectors, their linear kernel is:

\[k(x, y) = x^\top y\]

8.8.3. Polynomial kernel

The function polynomial_kernel computes the degree-d polynomial kernel between two vectors. The polynomial kernel represents the similarity between two vectors. Conceptually, the polynomial kernel considers not only the similarity between vectors under the same dimension, but also across dimensions. When used in machine learning algorithms, this allows to account for feature interaction.

The polynomial kernel is defined as:

\[k(x, y) = (\gamma x^\top y +c_0)^d\]

where:

  • x, y are the input vectors

  • d is the kernel degree

If \(c_0 = 0\) the kernel is said to be homogeneous.

8.8.4. Sigmoid kernel

The function sigmoid_kernel computes the sigmoid kernel between two vectors. The sigmoid kernel is also known as hyperbolic tangent, or Multilayer Perceptron (because, in the neural network field, it is often used as neuron activation function). It is defined as:

\[k(x, y) = \tanh( \gamma x^\top y + c_0)\]

where:

  • x, y are the input vectors

  • \(\gamma\) is known as slope

  • \(c_0\) is known as intercept

8.8.5. RBF kernel

The function rbf_kernel computes the radial basis function (RBF) kernel between two vectors. This kernel is defined as:

\[k(x, y) = \exp( -\gamma \| x-y \|^2)\]

where x and y are the input vectors. If \(\gamma = \sigma^{-2}\) the kernel is known as the Gaussian kernel of variance \(\sigma^2\).

8.8.6. Laplacian kernel

The function laplacian_kernel is a variant on the radial basis function kernel defined as:

\[k(x, y) = \exp( -\gamma \| x-y \|_1)\]

where x and y are the input vectors and \(\|x-y\|_1\) is the Manhattan distance between the input vectors.

It has proven useful in ML applied to noiseless data. See e.g. Machine learning for quantum mechanics in a nutshell.

8.8.7. Chi-squared kernel

The chi-squared kernel is a very popular choice for training non-linear SVMs in computer vision applications. It can be computed using chi2_kernel and then passed to an SVC with kernel="precomputed":

>>> from sklearn.svm import SVC
>>> from sklearn.metrics.pairwise import chi2_kernel
>>> X = [[0, 1], [1, 0], [.2, .8], [.7, .3]]
>>> y = [0, 1, 0, 1]
>>> K = chi2_kernel(X, gamma=.5)
>>> K
array([[1.        , 0.36787944, 0.89483932, 0.58364548],
       [0.36787944, 1.        , 0.51341712, 0.83822343],
       [0.89483932, 0.51341712, 1.        , 0.7768366 ],
       [0.58364548, 0.83822343, 0.7768366 , 1.        ]])

>>> svm = SVC(kernel='precomputed').fit(K, y)
>>> svm.predict(K)
array([0, 1, 0, 1])

It can also be directly used as the kernel argument:

>>> svm = SVC(kernel=chi2_kernel).fit(X, y)
>>> svm.predict(X)
array([0, 1, 0, 1])

The chi squared kernel is given by

\[k(x, y) = \exp \left (-\gamma \sum_i \frac{(x[i] - y[i]) ^ 2}{x[i] + y[i]} \right )\]

The data is assumed to be non-negative, and is often normalized to have an L1-norm of one. The normalization is rationalized with the connection to the chi squared distance, which is a distance between discrete probability distributions.

The chi squared kernel is most commonly used on histograms (bags) of visual words.

References

LLM07:2025 System Prompt Leakage

Assigned source reading · OWASP GenAI Security Project contributors

Copyright © 2025 OWASP Foundation, Inc. and contributors. OWASP trademarks are excluded.

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.

LLM07:2025 System Prompt Leakage

The system prompt leakage vulnerability in LLMs refers to the risk that the system prompts or instructions used to steer the behavior of the model can also contain sensitive information that was not intended to be discovered. System prompts are designed to guide the model’s output based on the requirements of the application, but may inadvertently contain secrets. When discovered, this information can be used to facilitate other attacks.

It’s important to understand that the system prompt should not be considered a secret, nor should it be used as a security control. Accordingly, sensitive data such as credentials, connection strings, etc. should not be contained within the system prompt language.

Similarly, if a system prompt contains information describing different roles and permissions, or sensitive data like connection strings or passwords, while the disclosure of such information may be helpful, the fundamental security risk is not that these have been disclosed, it is that the application allows bypassing strong session management and authorization checks by delegating these to the LLM, and that sensitive data is being stored in a place that it should not be.

In short: disclosure of the system prompt itself does not present the real risk — the security risk lies with the underlying elements, whether that be sensitive information disclosure, system guardrails bypass, improper separation of privileges, etc. Even if the exact wording is not disclosed, attackers interacting with the system will almost certainly be able to determine many of the guardrails and formatting restrictions that are present in system prompt language in the course of using the application, sending utterances to the model, and observing the results.

Common Examples of Risk

1. Exposure of Sensitive Functionality

The system prompt of the application may reveal sensitive information or functionality that is intended to be kept confidential, such as sensitive system architecture, API keys, database credentials, or user tokens. These can be extracted or used by attackers to gain unauthorized access into the application. For example, a system prompt that contains the type of database used for a tool could allow the attacker to target it for SQL injection attacks.

2. Exposure of Internal Rules

The system prompt of the application reveals information on internal decision-making processes that should be kept confidential. This information allows attackers to gain insights into how the application works which could allow attackers to exploit weaknesses or bypass controls in the application. For example – There is a banking application that has a chatbot and its system prompt may reveal information like >”The Transaction limit is set to $5000 per day for a user. The Total Loan Amount for a user is $10,000″. This information allows the attackers to bypass the security controls in the application like doing transactions more than the set limit or bypassing the total loan amount.

3. Revealing of Filtering Criteria

A system prompt might ask the model to filter or reject sensitive content. For example, a model might have a system prompt like, >“If a user requests information about another user, always respond with ‘Sorry, I cannot assist with that request’”.

4. Disclosure of Permissions and User Roles

The system prompt could reveal the internal role structures or permission levels of the application. For instance, a system prompt might reveal, >“Admin user role grants full access to modify user records.” If the attackers learn about these role-based permissions, they could look for a privilege escalation attack.

Prevention and Mitigation Strategies

1. Separate Sensitive Data from System Prompts

Avoid embedding any sensitive information (e.g. API keys, auth keys, database names, user roles, permission structure of the application) directly in the system prompts. Instead, externalize such information to the systems that the model does not directly access.

2. Avoid Reliance on System Prompts for Strict Behavior Control

Since LLMs are susceptible to other attacks like prompt injections which can alter the system prompt, it is recommended to avoid using system prompts to control the model behavior where possible. Instead, rely on systems outside of the LLM to ensure this behavior. For example, detecting and preventing harmful content should be done in external systems.

3. Implement Guardrails

Implement a system of guardrails outside of the LLM itself. While training particular behavior into a model can be effective, such as training it not to reveal its system prompt, it is not a guarantee that the model will always adhere to this. An independent system that can inspect the output to determine if the model is in compliance with expectations is preferable to system prompt instructions.

4. Ensure that security controls are enforced independently from the LLM

Critical controls such as privilege separation, authorization bounds checks, and similar must not be delegated to the LLM, either through the system prompt or otherwise. These controls need to occur in a deterministic, auditable manner, and LLMs are not (currently) conducive to this. In cases where an agent is performing tasks, if those tasks require different levels of access, then multiple agents should be used, each configured with the least privileges needed to perform the desired tasks.

Example Attack Scenarios

Scenario #1

An LLM has a system prompt that contains a set of credentials used for a tool that it has been given access to. The system prompt is leaked to an attacker, who then is able to use these credentials for other purposes.

Scenario #2

An LLM has a system prompt prohibiting the generation of offensive content, external links, and code execution. An attacker extracts this system prompt and then uses a prompt injection attack to bypass these instructions, facilitating a remote code execution attack.

Reference Links

  1. SYSTEM PROMPT LEAK: Pliny the prompter
  2. Prompt Leak: Prompt Security
  3. chatgpt_system_prompt: LouisShark
  4. leaked-system-prompts: Jujumilk3
  5. OpenAI Advanced Voice Mode System Prompt: Green_Terminals

Related Frameworks and Taxonomies

Refer to this section for comprehensive information, scenarios strategies relating to infrastructure deployment, applied environment controls and other best practices.

    LLM Top 10

    LLM01:2025 Prompt Injection

    A Prompt Injection Vulnerability occurs when user prompts alter the LLM’s behavior or output in unintended ways. These inputs...

    LLM02:2025 Sensitive Information Disclosure

    Sensitive information can affect both the LLM and its application context. This includes personal identifiable information (PII), financial details,...

    LLM03:2025 Supply Chain

    LLM supply chains are susceptible to various vulnerabilities, which can affect the integrity of training data, models, and deployment...

    LLM04:2025 Data and Model Poisoning

    Data poisoning occurs when pre-training, fine-tuning, or embedding data is manipulated to introduce vulnerabilities, backdoors, or biases. This manipulation...

    LLM05:2025 Improper Output Handling

    Improper Output Handling refers specifically to insufficient validation, sanitization, and handling of the outputs generated by large language models...

    LLM06:2025 Excessive Agency

    An LLM-based system is often granted a degree of agency by its developer – the ability to call functions...

    LLM07:2025 System Prompt Leakage

    The system prompt leakage vulnerability in LLMs refers to the risk that the system prompts or instructions used to...

    LLM08:2025 Vector and Embedding Weaknesses

    Vectors and embeddings vulnerabilities present significant security risks in systems utilizing Retrieval Augmented Generation (RAG) with Large Language Models...

    LLM09:2025 Misinformation

    Misinformation from LLMs poses a core vulnerability for applications relying on these models. Misinformation occurs when LLMs produce false...

    LLM10:2025 Unbounded Consumption

    Unbounded Consumption refers to the process where a Large Language Model (LLM) generates outputs based on input queries or...

    Django Tutorial Part 5: Creating our home page

    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 5: Creating our home page

    We're now ready to add the code that displays our first complete page — a home page for the LocalLibrary website. The home page will show the number of records we have for each model type and provide sidebar navigation links to our other pages. Along the way we'll gain practical experience in writing basic URL maps and views, getting records from the database, and using templates.

    Prerequisites: Read the Django Introduction. Complete previous tutorial topics (including Django Tutorial Part 4: Django admin site).
    Objective: Learn to create simple URL maps and views (where no data is encoded in the URL), get data from models, and create templates.

    Overview

    After we defined our models and created some initial library records to work with, it's time to write the code that presents that information to users. The first thing we need to do is determine what information we want to display in our pages, and define the URLs to use for returning those resources. Then we'll create a URL mapper, views, and templates to display the pages.

    The following diagram describes the main data flow, and the components required when handling HTTP requests and responses. As we already implemented the model, the main components we'll create are:

    • URL mappers to forward the supported URLs (and any information encoded in the URLs) to the appropriate view functions.
    • View functions to get the requested data from the models, create HTML pages that display the data, and return the pages to the user to view in the browser.
    • Templates to use when rendering data in the views.

    Main data flow diagram: URL, Model, View & Template component required when handling HTTP requests and responses in a Django application. A HTTP request hits a Django server gets forwarded to the 'urls.py' file of the URLS component. The request is forwarded to the appropriate view. The view can read and write data from the Models 'models.py' file containing the code related to models. The view also accesses the HTML file template component. The view returns the response back to the user.

    As you'll see in the next section, we have 5 pages to display, which is too much information to document in a single article. Therefore, this article will focus on how to implement the home page, and we'll cover the other pages in a subsequent article. This should give you a good end-to-end understanding of how URL mappers, views, and models work in practice.

    Defining the resource URLs

    As this version of LocalLibrary is essentially read-only for end users, we just need to provide a landing page for the site (a home page), and pages that display list and detail views for books and authors.

    The URLs that we'll need for our pages are:

    • catalog/ — The home (index) page.
    • catalog/books/ — A list of all books.
    • catalog/authors/ — A list of all authors.
    • catalog/book/<id> — The detail view for a particular book, with a field primary key of <id> (the default). For example, the URL for the third book added to the list will be /catalog/book/3.
    • catalog/author/<id> — The detail view for the specific author with a primary key field of <id>. For example, the URL for the 11th author added to the list will be /catalog/author/11.

    The first three URLs will return the index page, books list, and authors list. These URLs do not encode any additional information, and the queries that fetch data from the database will always be the same. However, the results that the queries return will depend on the contents of the database.

    By contrast the final two URLs will display detailed information about a specific book or author. These URLs encode the identity of the item to display (represented by <id> above). The URL mapper will extract the encoded information and pass it to the view, and the view will dynamically determine what information to get from the database. By encoding the information in the URL we will use a single set of a URL mapping, a view, and a template to handle all books (or authors).

    Note: With Django, you can construct your URLs however you require — you can encode information in the body of the URL as shown above, or include GET parameters in the URL, for example /book/?id=6. Whichever approach you use, the URLs should be kept clean, logical, and readable, as recommended by the W3C. The Django documentation recommends encoding information in the body of the URL to achieve better URL design.

    As mentioned in the overview, the rest of this article describes how to construct the index page.

    Creating the index page

    The first page we'll create is the index page (catalog/). The index page will include some static HTML, along with generated "counts" of different records in the database. To make this work we'll create a URL mapping, a view, and a template.

    Note: It's worth paying a little extra attention in this section. Most of the information also applies to the other pages we'll create.

    URL mapping

    When we created the skeleton website, we updated the locallibrary/urls.py file to ensure that whenever a URL that starts with catalog/ is received, the URLConf module catalog.urls will process the remaining substring.

    The following code snippet from locallibrary/urls.py includes the catalog.urls module:

    python
    urlpatterns += [
        path('catalog/', include('catalog.urls')),
    ]
    

    Note: Whenever Django encounters the import function django.urls.include(), it splits the URL string at the designated end character and sends the remaining substring to the included URLConf module for further processing.

    We also created a placeholder file for the URLConf module, named /catalog/urls.py. Add the following lines to that file:

    python
    urlpatterns = [
        path('', views.index, name='index'),
    ]
    

    The path() function defines the following:

    • A URL pattern, which is an empty string: ''. We'll discuss URL patterns in detail when working on the other views.
    • A view function that will be called if the URL pattern is detected: views.index, which is the function named index() in the views.py file.

    The path() function also specifies a name parameter, which is a unique identifier for this particular URL mapping. You can use the name to "reverse" the mapper, i.e., to dynamically create a URL that points to the resource that the mapper is designed to handle. For example, we can use the name parameter to link to our home page from any other page by adding the following link in a template:

    django
    <a href="{% url 'index' %}">Home</a>.
    

    Note: We can hard code the link (as in <a href="/catalog/">Home</a>), but if we change the pattern for our home page (for example, to /catalog/index) the templates will no longer link correctly. Using a reversed URL mapping is more robust.

    View (function-based)

    A view is a function that processes an HTTP request, fetches the required data from the database, renders the data in an HTML page using an HTML template, and then returns the generated HTML in an HTTP response to display the page to the user. The index view follows this model — it fetches information about the number of Book, BookInstance, available BookInstance and Author records that we have in the database, and passes that information to a template for display.

    Open catalog/views.py and note that the file already imports the render() shortcut function to generate an HTML file using a template and data:

    python
    from django.shortcuts import render
    
    # Create your views here.
    

    Paste the following lines at the bottom of the file:

    python
    from .models import Book, Author, BookInstance, Genre
    
    def index(request):
        """View function for home page of site."""
    
        # Generate counts of some of the main objects
        num_books = Book.objects.all().count()
        num_instances = BookInstance.objects.all().count()
    
        # Available books (status = 'a')
        num_instances_available = BookInstance.objects.filter(status__exact='a').count()
    
        # The 'all()' is implied by default.
        num_authors = Author.objects.count()
    
        context = {
            'num_books': num_books,
            'num_instances': num_instances,
            'num_instances_available': num_instances_available,
            'num_authors': num_authors,
        }
    
        # Render the HTML template index.html with the data in the context variable
        return render(request, 'index.html', context=context)
    

    The first line imports the model classes that we'll use to access data in all our views.

    The first part of the view function fetches the number of records using the objects.all() attribute on the model classes. It also gets a list of BookInstance objects that have a value of 'a' (Available) in the status field. You can find more information about how to access model data in our previous tutorial Django Tutorial Part 3: Using models > Searching for records.

    At the end of the view function we call the render() function to create an HTML page and return the page as a response. This shortcut function wraps a number of other functions to simplify a very common use case. The render() function accepts the following parameters:

    • the original request object, which is an HttpRequest.
    • an HTML template with placeholders for the data.
    • a context variable, which is a Python dictionary, containing the data to insert into the placeholders.

    We'll talk more about templates and the context variable in the next section. Let's get to creating our template so we can actually display something to the user!

    Template

    A template is a text file that defines the structure or layout of a file (such as an HTML page), it uses placeholders to represent actual content.

    A Django application created using startapp (like the skeleton of this example) will look for templates in a subdirectory named 'templates' of your applications. For example, in the index view that we just added, the render() function will expect to find the file index.html in /django-locallibrary-tutorial/catalog/templates/ and will raise an error if the file is not present.

    You can check this by saving the previous changes and accessing 127.0.0.1:8000 in your browser - it will display a fairly intuitive error message: "TemplateDoesNotExist at /catalog/", and other details.

    Note: Based on your project's settings file, Django will look for templates in a number of places, searching in your installed applications by default. You can find out more about how Django finds templates and what template formats it supports in the Templates section of the Django documentation.

    Extending templates

    The index template will need standard HTML markup for the head and body, along with navigation sections to link to the other pages of the site (which we haven't created yet), and to sections that display introductory text and book data.

    Much of the HTML and navigation structure will be the same in every page of our site. Instead of duplicating boilerplate code on every page, you can use the Django templating language to declare a base template, and then extend it to replace just the bits that are different for each specific page.

    The following code snippet is a sample base template from a base_generic.html file. We'll be creating the template for LocalLibrary shortly. The sample below includes common HTML with sections for a title, a sidebar, and main contents marked with the named block and endblock template tags. You can leave the blocks empty, or include default content to use when rendering pages derived from the template.

    Note: Template tags are functions that you can use in a template to loop through lists, perform conditional operations based on the value of a variable, and so on. In addition to template tags, the template syntax allows you to reference variables that are passed into the template from the view, and use template filters to format variables (for example, to convert a string to lower case).

    django
    <!doctype html>
    <html lang="en">
      <head>
        {% block title %}
          <title>Local Library</title>
        {% endblock %}
      </head>
      <body>
        {% block sidebar %}
          <!-- insert default navigation text for every page -->
        {% endblock %}
        {% block content %}
          <!-- default content text (typically empty) -->
        {% endblock %}
      </body>
    </html>
    

    When defining a template for a particular view, we first specify the base template using the extends template tag — see the code sample below. Then we declare what sections from the template we want to replace (if any), using block/endblock sections as in the base template.

    For example, the code snippet below shows how to use the extends template tag and override the content block. The generated HTML will include the code and structure defined in the base template, including the default content you defined in the title block, but the new content block in place of the default one.

    django
    {% extends "base_generic.html" %}
    
    {% block content %}
      <h1>Local Library Home</h1>
      <p>
        Welcome to LocalLibrary, a website developed by
        <em>Mozilla Developer Network</em>!
      </p>
    {% endblock %}
    

    The LocalLibrary base template

    We will use the following code snippet as the base template for the LocalLibrary website. As you can see, it contains some HTML code and defines blocks for title, sidebar, and content. We have a default title and a default sidebar with links to lists of all books and authors, both enclosed in blocks to be easily changed in the future.

    Note: We also introduce two additional template tags: url and load static. These tags will be explained in following sections.

    Create a new file base_generic.html in /django-locallibrary-tutorial/catalog/templates/ and paste the following code to the file:

    django
    <!doctype html>
    <html lang="en">
      <head>
        {% block title %}
          <title>Local Library</title>
        {% endblock %}
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
          rel="stylesheet"
          integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
          crossorigin="anonymous">
        <!-- Add additional CSS in static file -->
        {% load static %}
        <link rel="stylesheet" href="{% static 'css/styles.css' %}" />
      </head>
      <body>
        <div class="container-fluid">
          <div class="row">
            <div class="col-sm-2">
              {% block sidebar %}
                <ul class="sidebar-nav">
                  <li><a href="{% url 'index' %}">Home</a></li>
                  <li><a href="">All books</a></li>
                  <li><a href="">All authors</a></li>
                </ul>
              {% endblock %}
            </div>
            <div class="col-sm-10 ">{% block content %}{% endblock %}</div>
          </div>
        </div>
      </body>
    </html>
    

    The template includes CSS from Bootstrap to improve the layout and presentation of the HTML page. Using Bootstrap (or another client-side web framework) is a quick way to create an attractive page that displays well on different screen sizes.

    The base template also references a local CSS file (styles.css) that provides additional styling. Create a styles.css file in /django-locallibrary-tutorial/catalog/static/css/ and paste the following code in the file:

    css
    .sidebar-nav {
      margin-top: 20px;
      padding: 0;
      list-style: none;
    }
    

    The index template

    Create a new HTML file index.html in /django-locallibrary-tutorial/catalog/templates/ and paste the following code in the file. This code extends our base template on the first line, and then replaces the default content block for the template.

    django
    {% extends "base_generic.html" %}
    
    {% block content %}
      <h1>Local Library Home</h1>
      <p>
        Welcome to LocalLibrary, a website developed by
        <em>Mozilla Developer Network</em>!
      </p>
      <h2>Dynamic content</h2>
      <p>The library has the following record counts:</p>
      <ul>
        <li><strong>Books:</strong> {{ num_books }}</li>
        <li><strong>Copies:</strong> {{ num_instances }}</li>
        <li><strong>Copies available:</strong> {{ num_instances_available }}</li>
        <li><strong>Authors:</strong> {{ num_authors }}</li>
      </ul>
    {% endblock %}
    

    In the Dynamic content section we declare placeholders (template variables) for the information from the view that we want to include. The variables are enclosed with double brace (handlebars).

    Note: You can easily recognize template variables and template tags (functions) - variables are enclosed in double braces ({{ num_books }}), and tags are enclosed in single braces with percentage signs ({% extends "base_generic.html" %}).

    The important thing to note here is that variables are named with the keys that we pass into the context dictionary in the render() function of our view (see sample below). Variables will be replaced with their associated values when the template is rendered.

    python
    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }
    
    return render(request, 'index.html', context=context)
    

    Referencing static files in templates

    Your project is likely to use static resources, including JavaScript, CSS, and images. Because the location of these files might not be known (or might change), Django allows you to specify the location in your templates relative to the STATIC_URL global setting. The default skeleton website sets the value of STATIC_URL to "/static/", but you might choose to host these on a content delivery network or elsewhere.

    Within the template you first call the load template tag specifying "static" to add the template library, as shown in the code sample below. You can then use the static template tag and specify the relative URL to the required file.

    django
    <!-- Add additional CSS in static file -->
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/styles.css' %}" />
    

    You can add an image into the page in a similar way, for example:

    django
    {% load static %}
    <img
      src="{% static 'images/local_library_model_uml.png' %}"
      alt="UML diagram"
      style="width:555px;height:540px;" />
    

    Note: The samples above specify where the files are located, but Django does not serve them by default. We configured the development web server to serve files by modifying the global URL mapper (/django-locallibrary-tutorial/locallibrary/urls.py) when we created the website skeleton, but still need to enable file serving in production. We'll look at this later.

    For more information on working with static files see Managing static files in the Django documentation.

    Linking to URLs

    The base template above introduced the url template tag.

    django
    <li><a href="{% url 'index' %}">Home</a></li>
    

    This tag accepts the name of a path() function called in your urls.py and the values for any arguments that the associated view will receive from that function, and returns a URL that you can use to link to the resource.

    Configuring where to find the templates

    The location where Django searches for templates is specified in the TEMPLATES object in the settings.py file. The default settings.py (as created for this tutorial) looks something like this:

    python
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    

    The setting of 'APP_DIRS': True, is the most important, as it tells Django to search for templates in a subdirectory of each application in the project, named "templates" (this makes it easier to group templates with their associated application for easy re-use).

    We can also specify specific locations for Django to search for directories using 'DIRS': [] (but that isn't needed yet).

    Note: You can find out more about how Django finds templates and what template formats it supports in the Templates section of the Django documentation.

    What does it look like?

    At this point we have created all required resources to display the index page. Run the server (python3 manage.py runserver) and open http://127.0.0.1:8000/ in your browser. If everything is configured correctly, your site should look like the following screenshot.

    Index page for LocalLibrary website

    Note: The All books and All authors links will not work yet because the paths, views, and templates for those pages are not defined. We just inserted placeholders for those links in the base_generic.html template.

    Challenge yourself

    Here are a couple of tasks to test your familiarity with model queries, views, and templates.

    1. The LocalLibrary base template includes a title block. Override this block in the index template and create a new title for the page.

      Note: The section Extending templates explains how to create blocks and extend a block in another template.

    2. Modify the view to generate counts for genres and books that contain a particular word (case insensitive), and pass the results to the context. You accomplish this in a similar way to creating and using num_books and num_instances_available. Then update the index template to include these variables.

    Summary

    We just created the home page for our site — an HTML page that displays a number of records from the database and links to other yet-to-be-created pages. Along the way we learned fundamental information about URL mappers, views, querying the database with models, passing information to a template from a view, and creating and extending templates.

    In the next article we'll build upon this knowledge to create the remaining four pages of our website.

    See also