Complete Assigned Readings

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

9. Classes

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.

9. Classes

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.

Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++ and Modula-3. Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name. Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation.

In C++ terminology, normally class members (including the data members) are public (except see below Private Variables), and all member functions are virtual. As in Modula-3, there are no shorthands for referencing the object’s members from its methods: the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call. As in Smalltalk, classes themselves are objects. This provides semantics for importing and renaming. Unlike C++ and Modula-3, built-in types can be used as base classes for extension by the user. Also, like in C++, most built-in operators with special syntax (arithmetic operators, subscripting etc.) can be redefined for class instances.

(Lacking universally accepted terminology to talk about classes, I will make occasional use of Smalltalk and C++ terms. I would use Modula-3 terms, since its object-oriented semantics are closer to those of Python than C++, but I expect that few readers have heard of it.)

9.1. A Word About Names and Objects

Objects have individuality, and multiple names (in multiple scopes) can be bound to the same object. This is known as aliasing in other languages. This is usually not appreciated on a first glance at Python, and can be safely ignored when dealing with immutable basic types (numbers, strings, tuples). However, aliasing has a possibly surprising effect on the semantics of Python code involving mutable objects such as lists, dictionaries, and most other types. This is usually used to the benefit of the program, since aliases behave like pointers in some respects. For example, passing an object is cheap since only a pointer is passed by the implementation; and if a function modifies an object passed as an argument, the caller will see the change — this eliminates the need for two different argument passing mechanisms as in Pascal.

9.2. Python Scopes and Namespaces

Before introducing classes, I first have to tell you something about Python’s scope rules. Class definitions play some neat tricks with namespaces, and you need to know how scopes and namespaces work to fully understand what’s going on. Incidentally, knowledge about this subject is useful for any advanced Python programmer.

Let’s begin with some definitions.

A namespace is a mapping from names to objects. Most namespaces are currently implemented as Python dictionaries, but that’s normally not noticeable in any way (except for performance), and it may change in the future. Examples of namespaces are: the set of built-in names (containing functions such as abs(), and built-in exception names); the global names in a module; and the local names in a function invocation. In a sense the set of attributes of an object also form a namespace. The important thing to know about namespaces is that there is absolutely no relation between names in different namespaces; for instance, two different modules may both define a function maximize without confusion — users of the modules must prefix it with the module name.

By the way, I use the word attribute for any name following a dot — for example, in the expression z.real, real is an attribute of the object z. Strictly speaking, references to names in modules are attribute references: in the expression modname.funcname, modname is a module object and funcname is an attribute of it. In this case there happens to be a straightforward mapping between the module’s attributes and the global names defined in the module: they share the same namespace! [1]

Attributes may be read-only or writable. In the latter case, assignment to attributes is possible. Module attributes are writable: you can write modname.the_answer = 42. Writable attributes may also be deleted with the del statement. For example, del modname.the_answer will remove the attribute the_answer from the object named by modname.

Namespaces are created at different moments and have different lifetimes. The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted. The global namespace for a module is created when the module definition is read in; normally, module namespaces also last until the interpreter quits. The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, are considered part of a module called __main__, so they have their own global namespace. (The built-in names actually also live in a module; this is called builtins.)

The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that is not handled within the function. (Actually, forgetting would be a better way to describe what actually happens.) Of course, recursive invocations each have their own local namespace.

A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.

Although scopes are determined statically, they are used dynamically. At any time during execution, there are 3 or 4 nested scopes whose namespaces are directly accessible:

  • the innermost scope, which is searched first, contains the local names

  • the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contain non-local, but also non-global names

  • the next-to-last scope contains the current module’s global names

  • the outermost scope (searched last) is the namespace containing built-in names

If a name is declared global, then all references and assignments go directly to the next-to-last scope containing the module’s global names. To rebind variables found outside of the innermost scope, the nonlocal statement can be used; if not declared nonlocal, those variables are read-only (an attempt to write to such a variable will simply create a new local variable in the innermost scope, leaving the identically named outer variable unchanged).

Usually, the local scope references the local names of the (textually) current function. Outside functions, the local scope references the same namespace as the global scope: the module’s namespace. Class definitions place yet another namespace in the local scope.

It is important to realize that scopes are determined textually: the global scope of a function defined in a module is that module’s namespace, no matter from where or by what alias the function is called. On the other hand, the actual search for names is done dynamically, at run time — however, the language definition is evolving towards static name resolution, at “compile” time, so don’t rely on dynamic name resolution! (In fact, local variables are already determined statically.)

A special quirk of Python is that – if no global or nonlocal statement is in effect – assignments to names always go into the innermost scope. Assignments do not copy data — they just bind names to objects. The same is true for deletions: the statement del x removes the binding of x from the namespace referenced by the local scope. In fact, all operations that introduce new names use the local scope: in particular, import statements and function definitions bind the module or function name in the local scope.

The global statement can be used to indicate that particular variables live in the global scope and should be rebound there; the nonlocal statement indicates that particular variables live in an enclosing scope and should be rebound there.

9.2.1. Scopes and Namespaces Example

This is an example demonstrating how to reference the different scopes and namespaces, and how global and nonlocal affect variable binding:

def scope_test():
    def do_local():
        spam = "local spam"

    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)

The output of the example code is:

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

Note how the local assignment (which is default) didn’t change scope_test's binding of spam. The nonlocal assignment changed scope_test's binding of spam, and the global assignment changed the module-level binding.

You can also see that there was no previous binding for spam before the global assignment.

9.3. A First Look at Classes

Classes introduce a little bit of new syntax, three new object types, and some new semantics.

9.3.1. Class Definition Syntax

The simplest form of class definition looks like this:

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>

Class definitions, like function definitions (def statements) must be executed before they have any effect. (You could conceivably place a class definition in a branch of an if statement, or inside a function.)

In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful — we’ll come back to this later. The function definitions inside a class normally have a peculiar form of argument list, dictated by the calling conventions for methods — again, this is explained later.

When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here.

When a class definition is left normally (via the end), a class object is created. This is basically a wrapper around the contents of the namespace created by the class definition; we’ll learn more about class objects in the next section. The original local scope (the one in effect just before the class definition was entered) is reinstated, and the class object is bound here to the class name given in the class definition header (ClassName in the example).

9.3.2. Class Objects

Class objects support two kinds of operations: attribute references and instantiation.

Attribute references use the standard syntax used for all attribute references in Python: obj.name. Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this:

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of MyClass.i by assignment. __doc__ is also a valid attribute, returning the docstring belonging to the class: "A simple example class".

Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class):

x = MyClass()

creates a new instance of the class and assigns this object to the local variable x.

The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__(), like this:

def __init__(self):
    self.data = []

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly created class instance. So in this example, a new, initialized instance can be obtained by:

x = MyClass()

Of course, the __init__() method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to __init__(). For example,

>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)

9.3.3. Instance Objects

Now what can we do with instance objects? The only operations understood by instance objects are attribute references. There are two kinds of valid attribute names: data attributes and methods.

Data attributes correspond to “instance variables” in Smalltalk, and to “data members” in C++. Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to. For example, if x is the instance of MyClass created above, the following piece of code will print the value 16, without leaving a trace:

x.counter = 1
while x.counter < 10:
    x.counter = x.counter * 2
print(x.counter)
del x.counter

The other kind of instance attribute reference is a method. A method is a function that “belongs to” an object.

Valid method names of an instance object depend on its class. By definition, all attributes of a class that are function objects define corresponding methods of its instances. So in our example, x.f is a valid method reference, since MyClass.f is a function, but x.i is not, since MyClass.i is not. But x.f is not the same thing as MyClass.f — it is a method object, not a function object.

9.3.4. Method Objects

Usually, a method is called right after it is bound:

x.f()

If x = MyClass(), as above, this will return the string 'hello world'. However, it is not necessary to call a method right away: x.f is a method object, and can be stored away and called at a later time. For example:

xf = x.f
while True:
    print(xf())

will continue to print hello world until the end of time.

What exactly happens when a method is called? You may have noticed that x.f() was called without an argument above, even though the function definition for f() specified an argument. What happened to the argument? Surely Python raises an exception when a function that requires an argument is called without any — even if the argument isn’t actually used…

Actually, you may have guessed the answer: the special thing about methods is that the instance object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s instance object before the first argument.

In general, methods work as follows. When a non-data attribute of an instance is referenced, the instance’s class is searched. If the name denotes a valid class attribute that is a function object, references to both the instance object and the function object are packed into a method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.

9.3.5. Class and Instance Variables

Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:

class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs
'canine'
>>> e.kind                  # shared by all dogs
'canine'
>>> d.name                  # unique to d
'Fido'
>>> e.name                  # unique to e
'Buddy'

As discussed in A Word About Names and Objects, shared data can have possibly surprising effects involving mutable objects such as lists and dictionaries. For example, the tricks list in the following code should not be used as a class variable because just a single list would be shared by all Dog instances:

class Dog:

    tricks = []             # mistaken use of a class variable

    def __init__(self, name):
        self.name = name

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks                # unexpectedly shared by all dogs
['roll over', 'play dead']

Correct design of the class should use an instance variable instead:

class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']

9.4. Random Remarks

If the same attribute name occurs in both an instance and in a class, then attribute lookup prioritizes the instance:

>>> class Warehouse:
...    purpose = 'storage'
...    region = 'west'
...
>>> w1 = Warehouse()
>>> print(w1.purpose, w1.region)
storage west
>>> w2 = Warehouse()
>>> w2.region = 'east'
>>> print(w2.purpose, w2.region)
storage east

Data attributes may be referenced by methods as well as by ordinary users (“clients”) of an object. In other words, classes are not usable to implement pure abstract data types. In fact, nothing in Python makes it possible to enforce data hiding — it is all based upon convention. (On the other hand, the Python implementation, written in C, can completely hide implementation details and control access to an object if necessary; this can be used by extensions to Python written in C.)

Clients should use data attributes with care — clients may mess up invariants maintained by the methods by stamping on their data attributes. Note that clients may add data attributes of their own to an instance object without affecting the validity of the methods, as long as name conflicts are avoided — again, a naming convention can save a lot of headaches here.

There is no shorthand for referencing data attributes (or other methods!) from within methods. I find that this actually increases the readability of methods: there is no chance of confusing local variables and instance variables when glancing through a method.

Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.

Any function object that is a class attribute defines a method for instances of that class. It is not necessary that the function definition is textually enclosed in the class definition: assigning a function object to a local variable in the class is also ok. For example:

# Function defined outside the class
def f1(self, x, y):
    return min(x, x+y)

class C:
    f = f1

    def g(self):
        return 'hello world'

    h = g

Now f, g and h are all attributes of class C that refer to function objects, and consequently they are all methods of instances of C — h being exactly equivalent to g. Note that this practice usually only serves to confuse the reader of a program.

Methods may call other methods by using method attributes of the self argument:

class Bag:
    def __init__(self):
        self.data = []

    def add(self, x):
        self.data.append(x)

    def addtwice(self, x):
        self.add(x)
        self.add(x)

Methods may reference global names in the same way as ordinary functions. The global scope associated with a method is the module containing its definition. (A class is never used as a global scope.) While one rarely encounters a good reason for using global data in a method, there are many legitimate uses of the global scope: for one thing, functions and modules imported into the global scope can be used by methods, as well as functions and classes defined in it. Usually, the class containing the method is itself defined in this global scope, and in the next section we’ll find some good reasons why a method would want to reference its own class.

Each value is an object, and therefore has a class (also called its type). It is stored as object.__class__.

9.5. Inheritance

Of course, a language feature would not be worthy of the name “class” without supporting inheritance. The syntax for a derived class definition looks like this:

class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>

The name BaseClassName must be defined in a namespace accessible from the scope containing the derived class definition. In place of a base class name, other arbitrary expressions are also allowed. This can be useful, for example, when the base class is defined in another module:

class DerivedClassName(modname.BaseClassName):

Execution of a derived class definition proceeds the same as for a base class. When the class object is constructed, the base class is remembered. This is used for resolving attribute references: if a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class.

There’s nothing special about instantiation of derived classes: DerivedClassName() creates a new instance of the class. Method references are resolved as follows: the corresponding class attribute is searched, descending down the chain of base classes if necessary, and the method reference is valid if this yields a function object.

Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it. (For C++ programmers: all methods in Python are effectively virtual.)

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments). This is occasionally useful to clients as well. (Note that this only works if the base class is accessible as BaseClassName in the global scope.)

Python has two built-in functions that work with inheritance:

  • Use isinstance() to check an instance’s type: isinstance(obj, int) will be True only if obj.__class__ is int or some class derived from int.

  • Use issubclass() to check class inheritance: issubclass(bool, int) is True since bool is a subclass of int. However, issubclass(float, int) is False since float is not a subclass of int.

9.5.1. Multiple Inheritance

Python supports a form of multiple inheritance as well. A class definition with multiple base classes looks like this:

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>

For most purposes, in the simplest cases, you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy. Thus, if an attribute is not found in DerivedClassName, it is searched for in Base1, then (recursively) in the base classes of Base1, and if it was not found there, it was searched for in Base2, and so on.

In fact, it is slightly more complex than that; the method resolution order changes dynamically to support cooperative calls to super(). This approach is known in some other multiple-inheritance languages as call-next-method and is more powerful than the super call found in single-inheritance languages.

Dynamic ordering is necessary because all cases of multiple inheritance exhibit one or more diamond relationships (where at least one of the parent classes can be accessed through multiple paths from the bottommost class). For example, all classes inherit from object, so any case of multiple inheritance provides more than one path to reach object. To keep the base classes from being accessed more than once, the dynamic algorithm linearizes the search order in a way that preserves the left-to-right ordering specified in each class, that calls each parent only once, and that is monotonic (meaning that a class can be subclassed without affecting the precedence order of its parents). Taken together, these properties make it possible to design reliable and extensible classes with multiple inheritance. For more detail, see The Python 2.3 Method Resolution Order.

In some cases multiple inheritance is not allowed; see Multiple inheritance for details.

9.6. Private Variables

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

See also

The private name mangling specifications for details and special cases.

Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls. For example:

class Mapping:
    def __init__(self, iterable):
        self.items_list = []
        self.__update(iterable)

    def update(self, iterable):
        for item in iterable:
            self.items_list.append(item)

    __update = update   # private copy of original update() method

class MappingSubclass(Mapping):

    def update(self, keys, values):
        # provides new signature for update()
        # but does not break __init__()
        for item in zip(keys, values):
            self.items_list.append(item)

The above example would work even if MappingSubclass were to introduce a __update identifier since it is replaced with _Mapping__update in the Mapping class and _MappingSubclass__update in the MappingSubclass class respectively.

Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger.

Notice that code passed to exec() or eval() does not consider the classname of the invoking class to be the current class; this is similar to the effect of the global statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to getattr(), setattr() and delattr(), as well as when referencing __dict__ directly.

9.7. Odds and Ends

Sometimes it is useful to have a data type similar to the Pascal “record” or C “struct”, bundling together a few named data items. The idiomatic approach is to use dataclasses for this purpose:

from dataclasses import dataclass

@dataclass
class Employee:
    name: str
    dept: str
    salary: int
>>> john = Employee('john', 'computer lab', 1000)
>>> john.dept
'computer lab'
>>> john.salary
1000

A piece of Python code that expects a particular abstract data type can often be passed a class that emulates the methods of that data type instead. For instance, if you have a function that formats some data from a file object, you can define a class with methods read() and readline() that get the data from a string buffer instead, and pass it as an argument.

Instance method objects have attributes, too: m.__self__ is the instance object with the method m(), and m.__func__ is the function object corresponding to the method.

9.8. Iterators

By now you have probably noticed that most container objects can be looped over using a for statement:

for element in [1, 2, 3]:
    print(element)
for element in (1, 2, 3):
    print(element)
for key in {'one':1, 'two':2}:
    print(key)
for char in "123":
    print(char)
for line in open("myfile.txt"):
    print(line, end='')

This style of access is clear, concise, and convenient. The use of iterators pervades and unifies Python. Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method __next__() which accesses elements in the container one at a time. When there are no more elements, __next__() raises a StopIteration exception which tells the for loop to terminate. You can call the __next__() method using the next() built-in function; this example shows how it all works:

>>> s = 'abc'
>>> it = iter(s)
>>> it
<str_iterator object at 0x10c90e650>
>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
'c'
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    next(it)
StopIteration

Having seen the mechanics behind the iterator protocol, it is easy to add iterator behavior to your classes. Define an __iter__() method which returns an object with a __next__() method. If the class defines __next__(), then __iter__() can just return self:

class Reverse:
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]
>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
>>> for char in rev:
...     print(char)
...
m
a
p
s

9.9. Generators

Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed). An example shows that generators can be trivially easy to create:

def reverse(data):
    for index in range(len(data)-1, -1, -1):
        yield data[index]
>>> for char in reverse('golf'):
...     print(char)
...
f
l
o
g

Anything that can be done with generators can also be done with class-based iterators as described in the previous section. What makes generators so compact is that the __iter__() and __next__() methods are created automatically.

Another key feature is that the local variables and execution state are automatically saved between calls. This made the function easier to write and much more clear than an approach using instance variables like self.index and self.data.

In addition to automatic method creation and saving program state, when generators terminate, they automatically raise StopIteration. In combination, these features make it easy to create iterators with no more effort than writing a regular function.

9.10. Generator Expressions

Some simple generators can be coded succinctly as expressions using a syntax similar to list comprehensions but with parentheses instead of square brackets. These expressions are designed for situations where the generator is used right away by an enclosing function. Generator expressions are more compact but less versatile than full generator definitions and tend to be more memory friendly than equivalent list comprehensions.

Examples:

>>> sum(i*i for i in range(10))                 # sum of squares
285

>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec))         # dot product
260

>>> unique_words = set(word for line in page  for word in line.split())

>>> valedictorian = max((student.gpa, student.name) for student in graduates)

>>> data = 'golf'
>>> list(data[i] for i in range(len(data)-1, -1, -1))
['f', 'l', 'o', 'g']

>>> x = [[1,2,3], [], [4, 5]]
>>> g = (*i for i in x)
>>> list(g)
[1, 2, 3, 4, 5]

In most cases, generator expressions must be wrapped in parentheses. As a special case, however, when provided as the sole argument to a function (as in the examples involving sum, set, max, and list above), the generator expression does not need to be wrapped in an additional set of parentheses. That is to say, the following two pieces of code are semantically equivalent:

>>> f(x for x in y)
>>> f((x for x in y))

as are the following:

>>> f(*x for x in y)
>>> f((*x for x in y))

Footnotes

1 . 8 Discussion and Exercises

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

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

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

1.8 Discussion and Exercises

The List, USet, and SSet interfaces described in Section 1.2 are influenced by the Java Collections Framework [54]. These are essentially simplified versions of the List, Set, Map, SortedSet, and SortedMap interfaces found in the Java Collections Framework.

For a superb (and free) treatment of the mathematics discussed in this chapter, including asymptotic notation, logarithms, factorials, Stirling's approximation, basic probability, and lots more, see the textbook by Leyman, Leighton, and Meyer [50]. For a gentle calculus text that includes formal definitions of exponentials and logarithms, see the (freely available) classic text by Thompson [71].

For more information on basic probability, especially as it relates to computer science, see the textbook by Ross [63]. Another good reference, which covers both asymptotic notation and probability, is the textbook by Graham, Knuth, and Patashnik [37].

Exercise 1..1   This exercise is designed to help familiarize the reader with choosing the right data structure for the right problem. If implemented, the parts of this exercise should be done by making use of an implementation of the relevant interface (Stack, Queue, Deque, USet, or SSet) provided by the .

Solve the following problems by reading a text file one line at a time and performing operations on each line in the appropriate data structure(s). Your implementations should be fast enough that even files containing a million lines can be processed in a few seconds.

  1. Read the input one line at a time and then write the lines out in reverse order, so that the last input line is printed first, then the second last input line, and so on.

  2. Read the first 50 lines of input and then write them out in reverse order. Read the next 50 lines and then write them out in reverse order. Do this until there are no more lines left to read, at which point any remaining lines should be output in reverse order.

    In other words, your output will start with the 50th line, then the 49th, then the 48th, and so on down to the first line. This will be followed by the 100th line, followed by the 99th, and so on down to the 51st line. And so on.

    Your code should never have to store more than 50 lines at any given time.

  3. Read the input one line at a time. At any point after reading the first 42 lines, if some line is blank (i.e., a string of length 0), then output the line that occured 42 lines prior to that one. For example, if Line 242 is blank, then your program should output line 200. This program should be implemented so that it never stores more than 43 lines of the input at any given time.

  4. Read the input one line at a time and write each line to the output if it is not a duplicate of some previous input line. Take special care so that a file with a lot of duplicate lines does not use more memory than what is required for the number of unique lines.

  5. Read the input one line at a time and write each line to the output only if you have already read this line before. (The end result is that you remove the first occurrence of each line.) Take special care so that a file with a lot of duplicate lines does not use more memory than what is required for the number of unique lines.

  6. Read the entire input one line at a time. Then output all lines sorted by length, with the shortest lines first. In the case where two lines have the same length, resolve their order using the usual ``sorted order.'' Duplicate lines should be printed only once.

  7. Do the same as the previous question except that duplicate lines should be printed the same number of times that they appear in the input.

  8. Read the entire input one line at a time and then output the even numbered lines (starting with the first line, line 0) followed by the odd-numbered lines.

  9. Read the entire input one line at a time and randomly permute the lines before outputting them. To be clear: You should not modify the contents of any line. Instead, the same collection of lines should be printed, but in a random order.

Exercise 1..2   A Dyck word is a sequence of +1's and -1's with the property that the sum of any prefix of the sequence is never negative. For example, $ +1,-1,+1,-1$ is a Dyck word, but $ +1,-1,-1,+1$ is not a Dyck word since the prefix $ +1-1-1<0$. Describe any relationship between Dyck words and Stack $ \ensuremath{\mathrm{push}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{pop}()}$ operations.

Exercise 1..3   A matched string is a sequence of {, }, (, ), [, and ] characters that are properly matched. For example, ``{{()[]}}'' is a matched string, but this ``{{()]}'' is not, since the second { is matched with a ]. Show how to use a stack so that, given a string of length $ \ensuremath{\ensuremath{\mathit{n}}}$, you can determine if it is a matched string in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time.

Exercise 1..4   Suppose you have a Stack, $ \ensuremath{\ensuremath{\mathit{s}}}$, that supports only the $ \ensuremath{\mathrm{push}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{pop}()}$ operations. Show how, using only a FIFO Queue, $ \ensuremath{\ensuremath{\mathit{q}}}$, you can reverse the order of all elements in $ \ensuremath{\ensuremath{\mathit{s}}}$.

Exercise 1..5   Using a USet, implement a Bag. A Bag is like a USet--it supports the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ methods--but it allows duplicate elements to be stored. The $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation in a Bag returns some element (if any) that is equal to $ \ensuremath{\ensuremath{\mathit{x}}}$. In addition, a Bag supports the $ \ensuremath{\mathrm{find\_all}(\ensuremath{\mathit{x}})}$ operation that returns a list of all elements in the Bag that are equal to $ \ensuremath{\ensuremath{\mathit{x}}}$.

Exercise 1..6   From scratch, write and test implementations of the List, USet and SSet interfaces. These do not have to be efficient. They can be used later to test the correctness and performance of more efficient implementations. (The easiest way to do this is to store the elements in an array.)

Exercise 1..7   Work to improve the performance of your implementations from the previous question using any tricks you can think of. Experiment and think about how you could improve the performance of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ in your List implementation. Think about how you could improve the performance of the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation in your USet and SSet implementations. This exercise is designed to give you a feel for how difficult it can be to obtain efficient implementations of these interfaces.

opendatastructures.org

3 . 3 SEList: A Space-Efficient 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.3 SEList: A Space-Efficient Linked List

One of the drawbacks of linked lists (besides the time it takes to access elements that are deep within the list) is their space usage. Each node in a DLList requires an additional two references to the next and previous nodes in the list. Two of the fields in a Node are dedicated to maintaining the list, and only one of the fields is for storing data!

An SEList (space-efficient list) reduces this wasted space using a simple idea: Rather than store individual elements in a DLList, we store a block (array) containing several items. More precisely, an SEList is parameterized by a block size $ \ensuremath{\ensuremath{\mathit{b}}}$. Each individual node in an SEList stores a block that can hold up to $ \ensuremath{\ensuremath{\mathit{b}}+1}$ elements.

For reasons that will become clear later, it will be helpful if we can do Deque operations on each block. The data structure that we choose for this is a BDeque (bounded deque), derived from the ArrayDeque structure described in Section 2.4. The BDeque differs from the ArrayDeque in one small way: When a new BDeque is created, the size of the backing array $ \ensuremath{\ensuremath{\mathit{a}}}$ is fixed at $ \ensuremath{\ensuremath{\mathit{b}}+1}$ and never grows or shrinks. The important property of a BDeque is that it allows for the addition or removal of elements at either the front or back in constant time. This will be useful as elements are shifted from one block to another.

An SEList is just a doubly-linked list of blocks. In addition to $ \ensuremath{\ensuremath{\mathit{next}}}$ and $ \ensuremath{\ensuremath{\mathit{prev}}}$ pointers, each node $ \ensuremath{\ensuremath{\mathit{u}}}$ in an SEList contains a BDeque, $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{d}}}$.

3.3.1 Space Requirements

An SEList places very tight restrictions on the number of elements in a block: Unless a block is the last block, then that block contains at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$ and at most $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1$ elements. This means that, if an SEList contains $ \ensuremath{\ensuremath{\mathit{n}}}$ elements, then it has at most

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/(\ensuremath{\e...
...h{\ensuremath{\mathit{n}}}}/\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})
$

blocks. The BDeque for each block contains an array of length $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1$ but, for every block except the last, at most a constant amount of space is wasted in this array. The remaining memory used by a block is also constant. This means that the wasted space in an SEList is only $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})$. By choosing a value of $ \ensuremath{\ensuremath{\mathit{b}}}$ within a constant factor of $ \sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}$, we can make the space-overhead of an SEList approach the $ \sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}$ lower bound given in Section 2.6.2.

3.3.2 Finding Elements

The first challenge we face with an SEList is finding the list item with a given index $ \ensuremath{\ensuremath{\mathit{i}}}$. Note that the location of an element consists of two parts:

  1. The node $ \ensuremath{\ensuremath{\mathit{u}}}$ that contains the block that contains the element with index $ \ensuremath{\ensuremath{\mathit{i}}}$; and
  2. the index $ \ensuremath{\ensuremath{\mathit{j}}}$ of the element within its block.

To find the block that contains a particular element, we proceed the same way as we do in a DLList. We either start at the front of the list and traverse in the forward direction, or at the back of the list and traverse backwards until we reach the node we want. The only difference is that, each time we move from one node to the next, we skip over a whole block of elements.


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{get\_locatio...
...nsuremath{\mathit{i}}-\ensuremath{\mathit{idx}}}\\
\end{flushleft}\end{leftbar}

Remember that, with the exception of at most one block, each block contains at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$ elements, so each step in our search gets us $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$ elements closer to the element we are looking for. If we are searching forward, this means that we reach the node we want after $ O(1+\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}/\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})$ steps. If we search backwards, then we reach the node we want after $ O(1+(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}})/\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})$ steps. The algorithm takes the smaller of these two quantities depending on the value of $ \ensuremath{\ensuremath{\mathit{i}}}$, so the time to locate the item with index $ \ensuremath{\ensuremath{\mathit{i}}}$ is $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensur...
...{\ensuremath{\mathit{i}}}}\}/\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})$.

Once we know how to locate the item with index $ \ensuremath{\ensuremath{\mathit{i}}}$, the $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operations translate into getting or setting a particular index in the correct block:


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

The running times of these operations are dominated by the time it takes to locate the item, so they also run in $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensur...
...{\ensuremath{\mathit{i}}}}\}/\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})$ time.

3.3.3 Adding an Element

Adding elements to an SEList is a little more complicated. Before considering the general case, we consider the easier operation, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, in which $ \ensuremath{\ensuremath{\mathit{x}}}$ is added to the end of the list. If the last block is full (or does not exist because there are no blocks yet), then we first allocate a new block and append it to the list of blocks. Now that we are sure that the last block exists and is not full, we append $ \ensuremath{\ensuremath{\mathit{x}}}$ to the last block.


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{append}(\ens...
... \gets \ensuremath{\ensuremath{\mathit{n}} + 1}}\\
\end{flushleft}\end{leftbar}

Things get more complicated when we add to the interior of the list using $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$. We first locate $ \ensuremath{\ensuremath{\mathit{i}}}$ to get the node $ \ensuremath{\ensuremath{\mathit{u}}}$ whose block contains the $ \ensuremath{\ensuremath{\mathit{i}}}$th list item. The problem is that we want to insert $ \ensuremath{\ensuremath{\mathit{x}}}$ into $ \ensuremath{\ensuremath{\mathit{u}}}$'s block, but we have to be prepared for the case where $ \ensuremath{\ensuremath{\mathit{u}}}$'s block already contains $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1$ elements, so that it is full and there is no room for $ \ensuremath{\ensuremath{\mathit{x}}}$.

Let $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0,\ensuremath{\ensuremath{\e...
...math{\mathit{u}}}}_1,\ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_2,\ldots$ denote $ \ensuremath{\ensuremath{\mathit{u}}}$, $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{next}}}$, $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{next}}.\ensuremath{\mathit{next}}}$, and so on. We explore $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0,\ensuremath{\ensuremath{\e...
...math{\mathit{u}}}}_1,\ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_2,\ldots$ looking for a node that can provide space for $ \ensuremath{\ensuremath{\mathit{x}}}$. Three cases can occur during our space exploration (see Figure 3.4):

Figure 3.4: The three cases that occur during the addition of an item $ \ensuremath{\ensuremath{\mathit{x}}}$ in the interior of an SEList. (This SEList has block size $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}=3$.)
 \includegraphics[width=\textwidth ]{figs-python/selist-add-a}  
 \includegraphics[width=\textwidth ]{figs-python/selist-add-b}  
 \includegraphics[width=\textwidth ]{figs-python/selist-add-c}  

  1. We quickly (in $ r+1\le \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}$ steps) find a node $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_r$ whose block is not full. In this case, we perform $ r$ shifts of an element from one block into the next, so that the free space in $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_r$ becomes a free space in $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0$. We can then insert $ \ensuremath{\ensuremath{\mathit{x}}}$ into $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0$'s block.

  2. We quickly (in $ r+1\le \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}$ steps) run off the end of the list of blocks. In this case, we add a new empty block to the end of the list of blocks and proceed as in the first case.

  3. After $ \ensuremath{\ensuremath{\mathit{b}}}$ steps we do not find any block that is not full. In this case, $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0,\ldots,\ensuremath{\ensure...
...\ensuremath{\mathit{u}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1}$ is a sequence of $ \ensuremath{\ensuremath{\mathit{b}}}$ blocks that each contain $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1$ elements. We insert a new block $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}}$ at the end of this sequence and spread the original $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1)$ elements so that each block of $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}}$ contains exactly $ \ensuremath{\ensuremath{\mathit{b}}}$ elements. Now $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0$'s block contains only $ \ensuremath{\ensuremath{\mathit{b}}}$ elements so it has room for us to insert $ \ensuremath{\ensuremath{\mathit{x}}}$.


\begin{leftbar}
% latex2html id marker 14000\begin{flushleft}
\hspace*{1em} \e...
... \gets \ensuremath{\ensuremath{\mathit{n}} + 1}}\\
\end{flushleft}\end{leftbar}

The running time of the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operation depends on which of the three cases above occurs. Cases 1 and 2 involve examining and shifting elements through at most $ \ensuremath{\ensuremath{\mathit{b}}}$ blocks and take $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})$ time. Case 3 involves calling the $ \ensuremath{\mathrm{spread}(\ensuremath{\mathit{u}})}$ method, which moves $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1)$ elements and takes $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}^2)$ time. If we ignore the cost of Case 3 (which we will account for later with amortization) this means that the total running time to locate $ \ensuremath{\ensuremath{\mathit{i}}}$ and perform the insertion of $ \ensuremath{\ensuremath{\mathit{x}}}$ is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+\min\{\ensuremath{\ensurem...
...{\ensuremath{\mathit{i}}}}\}/\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})$.

3.3.4 Removing an Element

Removing an element from an SEList is similar to adding an element. We first locate the node $ \ensuremath{\ensuremath{\mathit{u}}}$ that contains the element with index $ \ensuremath{\ensuremath{\mathit{i}}}$. Now, we have to be prepared for the case where we cannot remove an element from $ \ensuremath{\ensuremath{\mathit{u}}}$ without causing $ \ensuremath{\ensuremath{\mathit{u}}}$'s block to become smaller than $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$.

Again, let $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0,\ensuremath{\ensuremath{\e...
...math{\mathit{u}}}}_1,\ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_2,\ldots$ denote $ \ensuremath{\ensuremath{\mathit{u}}}$, $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{next}}}$, $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{next}}.\ensuremath{\mathit{next}}}$, and so on. We examine $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0,\ensuremath{\ensuremath{\e...
...math{\mathit{u}}}}_1,\ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_2,\ldots$ in order to look for a node from which we can borrow an element to make the size of $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0$'s block at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$. There are three cases to consider (see Figure 3.5):

Figure 3.5: The three cases that occur during the removal of an item $ \ensuremath{\ensuremath{\mathit{x}}}$ in the interior of an SEList. (This SEList has block size $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}=3$.)
\includegraphics[scale=0.90909]{figs-python/selist-remove-a}
\includegraphics[scale=0.90909]{figs-python/selist-remove-b}
\includegraphics[scale=0.90909]{figs-python/selist-remove-c}

  1. We quickly (in $ r+1\le \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}$ steps) find a node whose block contains more than $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$ elements. In this case, we perform $ r$ shifts of an element from one block into the previous one, so that the extra element in $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_r$ becomes an extra element in $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0$. We can then remove the appropriate element from $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0$'s block.

  2. We quickly (in $ r+1\le \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}$ steps) run off the end of the list of blocks. In this case, $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_r$ is the last block, and there is no need for $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_r$'s block to contain at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$ elements. Therefore, we proceed as above, borrowing an element from $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_r$ to make an extra element in $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0$. If this causes $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_r$'s block to become empty, then we remove it.

  3. After $ \ensuremath{\ensuremath{\mathit{b}}}$ steps, we do not find any block containing more than $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$ elements. In this case, $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0,\ldots,\ensuremath{\ensure...
...\ensuremath{\mathit{u}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1}$ is a sequence of $ \ensuremath{\ensuremath{\mathit{b}}}$ blocks that each contain $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$ elements. We gather these $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1)$ elements into $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0,\ldots,\ensuremath{\ensure...
...\ensuremath{\mathit{u}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-2}$ so that each of these $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$ blocks contains exactly $ \ensuremath{\ensuremath{\mathit{b}}}$ elements and we remove $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1}$, which is now empty. Now $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0$'s block contains $ \ensuremath{\ensuremath{\mathit{b}}}$ elements and we can then remove the appropriate element from it.


\begin{leftbar}
% latex2html id marker 14215\begin{flushleft}
\hspace*{1em} \e...
... \gets \ensuremath{\ensuremath{\mathit{n}} - 1}}\\
\end{flushleft}\end{leftbar}

Like the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operation, the running time of the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operation is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+\min\{\ensuremath{\ensurem...
...{\ensuremath{\mathit{i}}}}\}/\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})$ if we ignore the cost of the $ \ensuremath{\mathrm{gather}(\ensuremath{\mathit{u}})}$ method that occurs in Case 3.

3.3.5 Amortized Analysis of Spreading and Gathering

Next, we consider the cost of the $ \ensuremath{\mathrm{gather}(\ensuremath{\mathit{u}})}$ and $ \ensuremath{\mathrm{spread}(\ensuremath{\mathit{u}})}$ methods that may be executed by the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ methods. For the sake of completeness, here they are:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{spread}(\ens...
...\gets \ensuremath{\ensuremath{\mathit{w}}.prev}}\\
\end{flushleft}\end{leftbar}

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

The running time of each of these methods is dominated by the two nested loops. Both the inner and outer loops execute at most $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1$ times, so the total running time of each of these methods is $ O((\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1)^2)=O(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}^2)$. However, the following lemma shows that these methods execute on at most one out of every $ \ensuremath{\ensuremath{\mathit{b}}}$ calls to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$.

Lemma 3..1   If an empty SEList is created and any sequence of $ m\ge 1$ calls to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ is performed, then the total time spent during all calls to $ \ensuremath{\mathrm{spread}()}$ and $ \ensuremath{\mathrm{gather}()}$ is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}m)$.

Proof. We will use the potential method of amortized analysis. We say that a node $ \ensuremath{\ensuremath{\mathit{u}}}$ is fragile if $ \ensuremath{\ensuremath{\mathit{u}}}$'s block does not contain $ \ensuremath{\ensuremath{\mathit{b}}}$ elements (so that $ \ensuremath{\ensuremath{\mathit{u}}}$ is either the last node, or contains $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$ or $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1$ elements). Any node whose block contains $ \ensuremath{\ensuremath{\mathit{b}}}$ elements is rugged. Define the potential of an SEList as the number of fragile nodes it contains. We will consider only the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operation and its relation to the number of calls to $ \ensuremath{\mathrm{spread}(\ensuremath{\mathit{u}})}$. The analysis of $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{gather}(\ensuremath{\mathit{u}})}$ is identical.

Notice that, if Case 1 occurs during the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ method, then only one node, $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_r$ has the size of its block changed. Therefore, at most one node, namely $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_r$, goes from being rugged to being fragile. If Case 2 occurs, then a new node is created, and this node is fragile, but no other node changes size, so the number of fragile nodes increases by one. Thus, in either Case 1 or Case 2 the potential of the SEList increases by at most one.

Finally, if Case 3 occurs, it is because $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0,\ldots,\ensuremath{\ensure...
...\ensuremath{\mathit{u}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1}$ are all fragile nodes. Then $ \ensuremath{\ensuremath{spread}(}u_0\ensuremath{)}$ is called and these $ \ensuremath{\ensuremath{\mathit{b}}}$ fragile nodes are replaced with $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1$ rugged nodes. Finally, $ \ensuremath{\ensuremath{\mathit{x}}}$ is added to $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0$'s block, making $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}_0$ fragile. In total the potential decreases by $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$.

In summary, the potential starts at 0 (there are no nodes in the list). Each time Case 1 or Case 2 occurs, the potential increases by at most 1. Each time Case 3 occurs, the potential decreases by $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$. The potential (which counts the number of fragile nodes) is never less than 0. We conclude that, for every occurrence of Case 3, there are at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$ occurrences of Case 1 or Case 2. Thus, for every call to $ \ensuremath{\mathrm{spread}(\ensuremath{\mathit{u}})}$ there are at least $ \ensuremath{\ensuremath{\mathit{b}}}$ calls to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$. This completes the proof. $ \qedsymbol$

3.3.6 Summary

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

Theorem 3..3   An SEList implements the List interface. Ignoring the cost of calls to $ \ensuremath{\mathrm{spread}(\ensuremath{\mathit{u}})}$ and $ \ensuremath{\mathrm{gather}(\ensuremath{\mathit{u}})}$, an SEList with block size $ \ensuremath{\ensuremath{\mathit{b}}}$ supports the operations
  • $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ in $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensur...
...{\ensuremath{\mathit{i}}}}\}/\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})$ time per operation; and
  • $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+\min\{\ensuremath{\ensurem...
...{\ensuremath{\mathit{i}}}}\}/\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})$ time per operation.
Furthermore, beginning with an empty SEList, any sequence of $ m$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operations results in a total of $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}m)$ time spent during all calls to $ \ensuremath{\mathrm{spread}(\ensuremath{\mathit{u}})}$ and $ \ensuremath{\mathrm{gather}(\ensuremath{\mathit{u}})}$.

The space (measured in words)3.1 used by an SEList that stores $ \ensuremath{\ensuremath{\mathit{n}}}$ elements is $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} +O(\ensuremath{\ensuremath{\...
...th{\ensuremath{\mathit{n}}}}/\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}})$.

The SEList is a trade-off between an ArrayList and a DLList where the relative mix of these two structures depends on the block size $ \ensuremath{\ensuremath{\mathit{b}}}$. At the extreme $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}=2$, each SEList node stores at most three values, which is not much different than a DLList. At the other extreme, $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}>\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$, all the elements are stored in a single array, just like in an ArrayList. In between these two extremes lies a trade-off between the time it takes to add or remove a list item and the time it takes to locate a particular list item.



Footnotes

... words)3.1
Recall Section 1.4 for a discussion of how memory is measured.
opendatastructures.org

9 . Red-Black 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.


9. Red-Black Trees

In this chapter, we present red-black trees, a version of binary search trees with logarithmic height. Red-black trees are one of the most widely used data structures. They appear as the primary search structure in many library implementations, including the Java Collections Framework and several implementations of the C++ Standard Template Library. They are also used within the Linux operating system kernel. There are several reasons for the popularity of red-black trees:

  1. A red-black tree storing $ \ensuremath{\ensuremath{\mathit{n}}}$ values has height at most $ 2\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$.
  2. The $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations on a red-black tree run in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ worst-case time.
  3. The amortized number of rotations performed during an $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation is constant.
The first two of these properties already put red-black trees ahead of skiplists, treaps, and scapegoat trees. Skiplists and treaps rely on randomization and their $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ running times are only expected. Scapegoat trees have a guaranteed bound on their height, but $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ only run in $ O(\log
\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ amortized time. The third property is just icing on the cake. It tells us that that the time needed to add or remove an element $ \ensuremath{\ensuremath{\mathit{x}}}$ is dwarfed by the time it takes to find $ \ensuremath{\ensuremath{\mathit{x}}}$.9.1

However, the nice properties of red-black trees come with a price: implementation complexity. Maintaining a bound of $ 2\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ on the height is not easy. It requires a careful analysis of a number of cases. We must ensure that the implementation does exactly the right thing in each case. One misplaced rotation or change of colour produces a bug that can be very difficult to understand and track down.

Rather than jumping directly into the implementation of red-black trees, we will first provide some background on a related data structure: 2-4 trees. This will give some insight into how red-black trees were discovered and why efficiently maintaining them is even possible.



Footnotes

....9.1
Note that skiplists and treaps also have this property in the expected sense. See Exercises 4.6 and 7.5.


Subsections
opendatastructures.org

9 . 2 RedBlackTree: A Simulated 2-4 Tree

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


9.2 RedBlackTree: A Simulated 2-4 Tree

A red-black tree is a binary search tree in which each node, $ \ensuremath{\ensuremath{\mathit{u}}}$, has a colour which is either red or black. Red is represented by the value 0 and black by the value $ 1$.

Before and after any operation on a red-black tree, the following two properties are satisfied. Each property is defined both in terms of the colours red and black, and in terms of the numeric values 0 and 1.

Property 9..3 (black-height)   There are the same number of black nodes on every root to leaf path. (The sum of the colours on any root to leaf path is the same.)

Property 9..4 (no-red-edge)   No two red nodes are adjacent. (For any node $ \ensuremath{\ensuremath{\mathit{u}}}$, except the root, $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{colour}}}}...
...h{\mathit{u}}.\ensuremath{\mathit{parent}}.\ensuremath{\mathit{colour}}}} \ge 1$.)

Notice that we can always colour the root, $ \ensuremath{\ensuremath{\mathit{r}}}$, of a red-black tree black without violating either of these two properties, so we will assume that the root is black, and the algorithms for updating a red-black tree will maintain this. Another trick that simplifies red-black trees is to treat the external nodes (represented by $ \ensuremath{\ensuremath{\mathit{nil}}}$) as black nodes. This way, every real node, $ \ensuremath{\ensuremath{\mathit{u}}}$, of a red-black tree has exactly two children, each with a well-defined colour. An example of a red-black tree is shown in Figure 9.4.

Figure 9.4: An example of a red-black tree with black-height 3. External ( $ \ensuremath{\ensuremath{\mathit{nil}}}$) nodes are drawn as squares.
\includegraphics[scale=0.90909]{figs-python/24rb-1}

9.2.1 Red-Black Trees and 2-4 Trees

At first it might seem surprising that a red-black tree can be efficiently updated to maintain the black-height and no-red-edge properties, and it seems unusual to even consider these as useful properties. However, red-black trees were designed to be an efficient simulation of 2-4 trees as binary trees.

Refer to Figure 9.5. Consider any red-black tree, $ T$, having $ \ensuremath{\ensuremath{\mathit{n}}}$ nodes and perform the following transformation: Remove each red node $ \ensuremath{\ensuremath{\mathit{u}}}$ and connect $ \ensuremath{\ensuremath{\mathit{u}}}$'s two children directly to the (black) parent of $ \ensuremath{\ensuremath{\mathit{u}}}$. After this transformation we are left with a tree $ T'$ having only black nodes.

Figure 9.5: Every red-black tree has a corresponding 2-4 tree.
\includegraphics[scale=0.90909]{figs-python/24rb-3}  
\includegraphics[scale=0.90909]{figs-python/24rb-2}  

Every internal node in $ T'$ has two, three, or four children: A black node that started out with two black children will still have two black children after this transformation. A black node that started out with one red and one black child will have three children after this transformation. A black node that started out with two red children will have four children after this transformation. Furthermore, the black-height property now guarantees that every root-to-leaf path in $ T'$ has the same length. In other words, $ T'$ is a 2-4 tree!

The 2-4 tree $ T'$ has $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1$ leaves that correspond to the $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1$ external nodes of the red-black tree. Therefore, this tree has height at most $ \log (\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1)$. Now, every root to leaf path in the 2-4 tree corresponds to a path from the root of the red-black tree $ T$ to an external node. The first and last node in this path are black and at most one out of every two internal nodes is red, so this path has at most $ \log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1)$ black nodes and at most $ \log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1)-1$ red nodes. Therefore, the longest path from the root to any internal node in $ T$ is at most

$\displaystyle 2\log(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1) -2 \le 2\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} \enspace ,
$

for any $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\ge 1$. This proves the most important property of red-black trees:

Lemma 9..2   The height of red-black tree with $ \ensuremath{\ensuremath{\mathit{n}}}$ nodes is at most $ 2\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$.

Now that we have seen the relationship between 2-4 trees and red-black trees, it is not hard to believe that we can efficiently maintain a red-black tree while adding and removing elements.

We have already seen that adding an element in a BinarySearchTree can be done by adding a new leaf. Therefore, to implement $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ in a red-black tree we need a method of simulating splitting a node with five children in a 2-4 tree. A 2-4 tree node with five children is represented by a black node that has two red children, one of which also has a red child. We can ``split'' this node by colouring it red and colouring its two children black. An example of this is shown in Figure 9.6.

Figure 9.6: Simulating a 2-4 tree split operation during an addition in a red-black tree. (This simulates the 2-4 tree addition shown in Figure 9.2.)
\includegraphics[scale=0.90909]{figs-python/rb-split-1}
\includegraphics[scale=0.90909]{figs-python/rb-split-2}
\includegraphics[scale=0.90909]{figs-python/rb-split-3}

Similarly, implementing $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ requires a method of merging two nodes and borrowing a child from a sibling. Merging two nodes is the inverse of a split (shown in Figure 9.6), and involves colouring two (black) siblings red and colouring their (red) parent black. Borrowing from a sibling is the most complicated of the procedures and involves both rotations and recolouring nodes.

Of course, during all of this we must still maintain the no-red-edge property and the black-height property. While it is no longer surprising that this can be done, there are a large number of cases that have to be considered if we try to do a direct simulation of a 2-4 tree by a red-black tree. At some point, it just becomes simpler to disregard the underlying 2-4 tree and work directly towards maintaining the properties of the red-black tree.

9.2.2 Left-Leaning Red-Black Trees

No single definition of red-black trees exists. Rather, there is a family of structures that manage to maintain the black-height and no-red-edge properties during $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations. Different structures do this in different ways. Here, we implement a data structure that we call a RedBlackTree. This structure implements a particular variant of red-black trees that satisfies an additional property:

Property 9..5 (left-leaning)   At any node $ \ensuremath{\ensuremath{\mathit{u}}}$, if $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}}$ is black, then $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$ is black.

Note that the red-black tree shown in Figure 9.4 does not satisfy the left-leaning property; it is violated by the parent of the red node in the rightmost path.

The reason for maintaining the left-leaning property is that it reduces the number of cases encountered when updating the tree during $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations. In terms of 2-4 trees, it implies that every 2-4 tree has a unique representation: A node of degree two becomes a black node with two black children. A node of degree three becomes a black node whose left child is red and whose right child is black. A node of degree four becomes a black node with two red children.

Before we describe the implementation of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ in detail, we first present some simple subroutines used by these methods that are illustrated in Figure 9.7. The first two subroutines are for manipulating colours while preserving the black-height property. The $ \ensuremath{\mathrm{push\_black}(\ensuremath{\mathit{u}})}$ method takes as input a black node $ \ensuremath{\ensuremath{\mathit{u}}}$ that has two red children and colours $ \ensuremath{\ensuremath{\mathit{u}}}$ red and its two children black. The $ \ensuremath{\mathrm{pull\_black}(\ensuremath{\mathit{u}})}$ method reverses this operation:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{push\_black}...
...athit{right}}.\ensuremath{\mathit{colour}} - 1}}\\
\end{flushleft}\end{leftbar}

Figure 9.7: Flips, pulls and pushes
\includegraphics[width=\textwidth ]{figs-python/flippullpush}

The $ \ensuremath{\mathrm{flip\_left}(\ensuremath{\mathit{u}})}$ method swaps the colours of $ \ensuremath{\ensuremath{\mathit{u}}}$ and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$ and then performs a left rotation at $ \ensuremath{\ensuremath{\mathit{u}}}$. This method reverses the colours of these two nodes as well as their parent-child relationship:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{flip\_left}(...
...{\mathrm{rotate\_left}(\ensuremath{\mathit{u}})}\\
\end{flushleft}\end{leftbar}
The $ \ensuremath{\mathrm{flip\_left}(\ensuremath{\mathit{u}})}$ operation is especially useful in restoring the left-leaning property at a node $ \ensuremath{\ensuremath{\mathit{u}}}$ that violates it (because $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}}$ is black and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$ is red). In this special case, we can be assured that this operation preserves both the black-height and no-red-edge properties. The $ \ensuremath{\mathrm{flip\_right}(\ensuremath{\mathit{u}})}$ operation is symmetric with $ \ensuremath{\mathrm{flip\_left}(\ensuremath{\mathit{u}})}$, when the roles of left and right are reversed.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{flip\_right}...
...\mathrm{rotate\_right}(\ensuremath{\mathit{u}})}\\
\end{flushleft}\end{leftbar}

9.2.3 Addition

To implement $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ in a RedBlackTree, we perform a standard BinarySearchTree insertion to add a new leaf, $ \ensuremath{\ensuremath{\mathit{u}}}$, with $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{x}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}$ and set $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{colour}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{red}}}}$. Note that this does not change the black height of any node, so it does not violate the black-height property. It may, however, violate the left-leaning property (if $ \ensuremath{\ensuremath{\mathit{u}}}$ is the right child of its parent), and it may violate the no-red-edge property (if $ \ensuremath{\ensuremath{\mathit{u}}}$'s parent is $ \ensuremath{\ensuremath{\mathit{red}}}$). To restore these properties, we call the method $ \ensuremath{\mathrm{add\_fixup}(\ensuremath{\mathit{u}})}$.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
...eturn}} \ensuremath{\ensuremath{\mathit{false}}}\\
\end{flushleft}\end{leftbar}

Illustrated in Figure 9.8, the $ \ensuremath{\mathrm{add\_fixup}(\ensuremath{\mathit{u}})}$ method takes as input a node $ \ensuremath{\ensuremath{\mathit{u}}}$ whose colour is red and which may violate the no-red-edge property and/or the left-leaning property. The following discussion is probably impossible to follow without referring to Figure 9.8 or recreating it on a piece of paper. Indeed, the reader may wish to study this figure before continuing.

Figure 9.8: A single round in the process of fixing Property 2 after an insertion.
\includegraphics[width=\textwidth ]{figs-python/rb-addfix}

If $ \ensuremath{\ensuremath{\mathit{u}}}$ is the root of the tree, then we can colour $ \ensuremath{\ensuremath{\mathit{u}}}$ black to restore both properties. If $ \ensuremath{\ensuremath{\mathit{u}}}$'s sibling is also red, then $ \ensuremath{\ensuremath{\mathit{u}}}$'s parent must be black, so both the left-leaning and no-red-edge properties already hold.

Otherwise, we first determine if $ \ensuremath{\ensuremath{\mathit{u}}}$'s parent, $ \ensuremath{\ensuremath{\mathit{w}}}$, violates the left-leaning property and, if so, perform a $ \ensuremath{\mathrm{flip\_left}(\ensuremath{\mathit{w}})}$ operation and set $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$. This leaves us in a well-defined state: $ \ensuremath{\ensuremath{\mathit{u}}}$ is the left child of its parent, $ \ensuremath{\ensuremath{\mathit{w}}}$, so $ \ensuremath{\ensuremath{\mathit{w}}}$ now satisfies the left-leaning property. All that remains is to ensure the no-red-edge property at $ \ensuremath{\ensuremath{\mathit{u}}}$. We only have to worry about the case in which $ \ensuremath{\ensuremath{\mathit{w}}}$ is red, since otherwise $ \ensuremath{\ensuremath{\mathit{u}}}$ already satisfies the no-red-edge property.

Since we are not done yet, $ \ensuremath{\ensuremath{\mathit{u}}}$ is red and $ \ensuremath{\ensuremath{\mathit{w}}}$ is red. The no-red-edge property (which is only violated by $ \ensuremath{\ensuremath{\mathit{u}}}$ and not by $ \ensuremath{\ensuremath{\mathit{w}}}$) implies that $ \ensuremath{\ensuremath{\mathit{u}}}$'s grandparent $ \ensuremath{\ensuremath{\mathit{g}}}$ exists and is black. If $ \ensuremath{\ensuremath{\mathit{g}}}$'s right child is red, then the left-leaning property ensures that both $ \ensuremath{\ensuremath{\mathit{g}}}$'s children are red, and a call to $ \ensuremath{\mathrm{push\_black}(\ensuremath{\mathit{g}})}$ makes $ \ensuremath{\ensuremath{\mathit{g}}}$ red and $ \ensuremath{\ensuremath{\mathit{w}}}$ black. This restores the no-red-edge property at $ \ensuremath{\ensuremath{\mathit{u}}}$, but may cause it to be violated at $ \ensuremath{\ensuremath{\mathit{g}}}$, so the whole process starts over with $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{g}}}}$.

If $ \ensuremath{\ensuremath{\mathit{g}}}$'s right child is black, then a call to $ \ensuremath{\mathrm{flip\_right}(\ensuremath{\mathit{g}})}$ makes $ \ensuremath{\ensuremath{\mathit{w}}}$ the (black) parent of $ \ensuremath{\ensuremath{\mathit{g}}}$ and gives $ \ensuremath{\ensuremath{\mathit{w}}}$ two red children, $ \ensuremath{\ensuremath{\mathit{u}}}$ and $ \ensuremath{\ensuremath{\mathit{g}}}$. This ensures that $ \ensuremath{\ensuremath{\mathit{u}}}$ satisfies the no-red-edge property and $ \ensuremath{\ensuremath{\mathit{g}}}$ satisfies the left-leaning property. In this case we can stop.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add\_fixup}(...
...th{\ensuremath{\mathit{u}} \gets \ensuremath{g}}\\
\end{flushleft}\end{leftbar}

The $ \ensuremath{\mathrm{insert\_fixup}(\ensuremath{\mathit{u}})}$ method takes constant time per iteration and each iteration either finishes or moves $ \ensuremath{\ensuremath{\mathit{u}}}$ closer to the root. Therefore, the $ \ensuremath{\mathrm{insert\_fixup}(\ensuremath{\mathit{u}})}$ method finishes after $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ iterations in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time.

9.2.4 Removal

The $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation in a RedBlackTree is the most complicated to implement, and this is true of all known red-black tree variants. Just like the $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation in a BinarySearchTree, this operation boils down to finding a node $ \ensuremath{\ensuremath{\mathit{w}}}$ with only one child, $ \ensuremath{\ensuremath{\mathit{u}}}$, and splicing $ \ensuremath{\ensuremath{\mathit{w}}}$ out of the tree by having $ \ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{parent}}}$ adopt $ \ensuremath{\ensuremath{\mathit{u}}}$.

The problem with this is that, if $ \ensuremath{\ensuremath{\mathit{w}}}$ is black, then the black-height property will now be violated at $ \ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{parent}}}$. We may avoid this problem, temporarily, by adding $ \ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{colour}}}$ to $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{colour}}}$. Of course, this introduces two other problems: (1) if $ \ensuremath{\ensuremath{\mathit{u}}}$ and $ \ensuremath{\ensuremath{\mathit{w}}}$ both started out black, then $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{colour}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{colour}}}}=2$ (double black), which is an invalid colour. If $ \ensuremath{\ensuremath{\mathit{w}}}$ was red, then it is replaced by a black node $ \ensuremath{\ensuremath{\mathit{u}}}$, which may violate the left-leaning property at $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{parent}}}}$. Both of these problems can be resolved with a call to the $ \ensuremath{\mathrm{remove\_fixup}(\ensuremath{\mathit{u}})}$ method.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}(\ens...
...return}} \ensuremath{\ensuremath{\mathit{true}}}\\
\end{flushleft}\end{leftbar}

The $ \ensuremath{\mathrm{remove\_fixup}(\ensuremath{\mathit{u}})}$ method takes as its input a node $ \ensuremath{\ensuremath{\mathit{u}}}$ whose colour is black (1) or double-black (2). If $ \ensuremath{\ensuremath{\mathit{u}}}$ is double-black, then $ \ensuremath{\mathrm{remove\_fixup}(\ensuremath{\mathit{u}})}$ performs a series of rotations and recolouring operations that move the double-black node up the tree until it can be eliminated. During this process, the node $ \ensuremath{\ensuremath{\mathit{u}}}$ changes until, at the end of this process, $ \ensuremath{\ensuremath{\mathit{u}}}$ refers to the root of the subtree that has been changed. The root of this subtree may have changed colour. In particular, it may have gone from red to black, so the $ \ensuremath{\mathrm{remove\_fixup}(\ensuremath{\mathit{u}})}$ method finishes by checking if $ \ensuremath{\ensuremath{\mathit{u}}}$'s parent violates the left-leaning property and, if so, fixing it.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove\_fixu...
...th{\mathrm{flip\_left}(\ensuremath{\mathit{w}})}\\
\end{flushleft}\end{leftbar}

The $ \ensuremath{\mathrm{remove\_fixup}(\ensuremath{\mathit{u}})}$ method is illustrated in Figure 9.9. Again, the following text will be difficult, if not impossible, to follow without referring to Figure 9.9. Each iteration of the loop in $ \ensuremath{\mathrm{remove\_fixup}(\ensuremath{\mathit{u}})}$ processes the double-black node $ \ensuremath{\ensuremath{\mathit{u}}}$, based on one of four cases:

Figure 9.9: A single round in the process of eliminating a double-black node after a removal.
\includegraphics[height=\textheight ]{figs-python/rb-removefix}

Case 0: $ \ensuremath{\ensuremath{\mathit{u}}}$ is the root. This is the easiest case to treat. We recolour $ \ensuremath{\ensuremath{\mathit{u}}}$ to be black (this does not violate any of the red-black tree properties).

Case 1: $ \ensuremath{\ensuremath{\mathit{u}}}$'s sibling, $ \ensuremath{\ensuremath{\mathit{v}}}$, is red. In this case, $ \ensuremath{\ensuremath{\mathit{u}}}$'s sibling is the left child of its parent, $ \ensuremath{\ensuremath{\mathit{w}}}$ (by the left-leaning property). We perform a right-flip at $ \ensuremath{\ensuremath{\mathit{w}}}$ and then proceed to the next iteration. Note that this action causes $ \ensuremath{\ensuremath{\mathit{w}}}$'s parent to violate the left-leaning property and the depth of $ \ensuremath{\ensuremath{\mathit{u}}}$ to increase. However, it also implies that the next iteration will be in Case 3 with $ \ensuremath{\ensuremath{\mathit{w}}}$ coloured red. When examining Case 3 below, we will see that the process will stop during the next iteration.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove\_fixu...
...bf{return}} \ensuremath{\ensuremath{\mathit{u}}}\\
\end{flushleft}\end{leftbar}

Case 2: $ \ensuremath{\ensuremath{\mathit{u}}}$'s sibling, $ \ensuremath{\ensuremath{\mathit{v}}}$, is black, and $ \ensuremath{\ensuremath{\mathit{u}}}$ is the left child of its parent, $ \ensuremath{\ensuremath{\mathit{w}}}$. In this case, we call $ \ensuremath{\mathrm{pull\_black}(\ensuremath{\mathit{w}})}$, making $ \ensuremath{\ensuremath{\mathit{u}}}$ black, $ \ensuremath{\ensuremath{\mathit{v}}}$ red, and darkening the colour of $ \ensuremath{\ensuremath{\mathit{w}}}$ to black or double-black. At this point, $ \ensuremath{\ensuremath{\mathit{w}}}$ does not satisfy the left-leaning property, so we call $ \ensuremath{\mathrm{flip\_left}(\ensuremath{\mathit{w}})}$ to fix this.

At this point, $ \ensuremath{\ensuremath{\mathit{w}}}$ is red and $ \ensuremath{\ensuremath{\mathit{v}}}$ is the root of the subtree with which we started. We need to check if $ \ensuremath{\ensuremath{\mathit{w}}}$ causes the no-red-edge property to be violated. We do this by inspecting $ \ensuremath{\ensuremath{\mathit{w}}}$'s right child, $ \ensuremath{\ensuremath{\mathit{q}}}$. If $ \ensuremath{\ensuremath{\mathit{q}}}$ is black, then $ \ensuremath{\ensuremath{\mathit{w}}}$ satisfies the no-red-edge property and we can continue the next iteration with $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{v}}}}$.

Otherwise ( $ \ensuremath{\ensuremath{\mathit{q}}}$ is red), so both the no-red-edge property and the left-leaning properties are violated at $ \ensuremath{\ensuremath{\mathit{q}}}$ and $ \ensuremath{\ensuremath{\mathit{w}}}$, respectively. The left-leaning property is restored with a call to $ \ensuremath{\mathrm{rotate\_left}(\ensuremath{\mathit{w}})}$, but the no-red-edge property is still violated. At this point, $ \ensuremath{\ensuremath{\mathit{q}}}$ is the left child of $ \ensuremath{\ensuremath{\mathit{v}}}$, $ \ensuremath{\ensuremath{\mathit{w}}}$ is the left child of $ \ensuremath{\ensuremath{\mathit{q}}}$, $ \ensuremath{\ensuremath{\mathit{q}}}$ and $ \ensuremath{\ensuremath{\mathit{w}}}$ are both red, and $ \ensuremath{\ensuremath{\mathit{v}}}$ is black or double-black. A $ \ensuremath{\mathrm{flip\_right}(\ensuremath{\mathit{v}})}$ makes $ \ensuremath{\ensuremath{\mathit{q}}}$ the parent of both $ \ensuremath{\ensuremath{\mathit{v}}}$ and $ \ensuremath{\ensuremath{\mathit{w}}}$. Following this up by a $ \ensuremath{\mathrm{push\_black}(\ensuremath{\mathit{q}})}$ makes both $ \ensuremath{\ensuremath{\mathit{v}}}$ and $ \ensuremath{\ensuremath{\mathit{w}}}$ black and sets the colour of $ \ensuremath{\ensuremath{\mathit{q}}}$ back to the original colour of $ \ensuremath{\ensuremath{\mathit{w}}}$.

At this point, the double-black node is has been eliminated and the no-red-edge and black-height properties are reestablished. Only one possible problem remains: the right child of $ \ensuremath{\ensuremath{\mathit{v}}}$ may be red, in which case the left-leaning property would be violated. We check this and perform a $ \ensuremath{\mathrm{flip\_left}(\ensuremath{\mathit{v}})}$ to correct it if necessary.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove\_fixu...
...bf{return}} \ensuremath{\ensuremath{\mathit{v}}}\\
\end{flushleft}\end{leftbar}

Case 3: $ \ensuremath{\ensuremath{\mathit{u}}}$'s sibling is black and $ \ensuremath{\ensuremath{\mathit{u}}}$ is the right child of its parent, $ \ensuremath{\ensuremath{\mathit{w}}}$. This case is symmetric to Case 2 and is handled mostly the same way. The only differences come from the fact that the left-leaning property is asymmetric, so it requires different handling.

As before, we begin with a call to $ \ensuremath{\mathrm{pull\_black}(\ensuremath{\mathit{w}})}$, which makes $ \ensuremath{\ensuremath{\mathit{v}}}$ red and $ \ensuremath{\ensuremath{\mathit{u}}}$ black. A call to $ \ensuremath{\mathrm{flip\_right}(\ensuremath{\mathit{w}})}$ promotes $ \ensuremath{\ensuremath{\mathit{v}}}$ to the root of the subtree. At this point $ \ensuremath{\ensuremath{\mathit{w}}}$ is red, and the code branches two ways depending on the colour of $ \ensuremath{\ensuremath{\mathit{w}}}$'s left child, $ \ensuremath{\ensuremath{\mathit{q}}}$.

If $ \ensuremath{\ensuremath{\mathit{q}}}$ is red, then the code finishes up exactly the same way as Case 2 does, but is even simpler since there is no danger of $ \ensuremath{\ensuremath{\mathit{v}}}$ not satisfying the left-leaning property.

The more complicated case occurs when $ \ensuremath{\ensuremath{\mathit{q}}}$ is black. In this case, we examine the colour of $ \ensuremath{\ensuremath{\mathit{v}}}$'s left child. If it is red, then $ \ensuremath{\ensuremath{\mathit{v}}}$ has two red children and its extra black can be pushed down with a call to $ \ensuremath{\mathrm{push\_black}(\ensuremath{\mathit{v}})}$. At this point, $ \ensuremath{\ensuremath{\mathit{v}}}$ now has $ \ensuremath{\ensuremath{\mathit{w}}}$'s original colour, and we are done.

If $ \ensuremath{\ensuremath{\mathit{v}}}$'s left child is black, then $ \ensuremath{\ensuremath{\mathit{v}}}$ violates the left-leaning property, and we restore this with a call to $ \ensuremath{\mathrm{flip\_left}(\ensuremath{\mathit{v}})}$. We then return the node $ \ensuremath{\ensuremath{\mathit{v}}}$ so that the next iteration of $ \ensuremath{\mathrm{remove\_fixup}(\ensuremath{\mathit{u}})}$ then continues with $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{v}}}}$.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove\_fixu...
...bf{return}} \ensuremath{\ensuremath{\mathit{w}}}\\
\end{flushleft}\end{leftbar}

Each iteration of $ \ensuremath{\mathrm{remove\_fixup}(\ensuremath{\mathit{u}})}$ takes constant time. Cases 2 and 3 either finish or move $ \ensuremath{\ensuremath{\mathit{u}}}$ closer to the root of the tree. Case 0 (where $ \ensuremath{\ensuremath{\mathit{u}}}$ is the root) always terminates and Case 1 leads immediately to Case 3, which also terminates. Since the height of the tree is at most $ 2\log
\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$, we conclude that there are at most $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ iterations of $ \ensuremath{\mathrm{remove\_fixup}(\ensuremath{\mathit{u}})}$, so $ \ensuremath{\mathrm{remove\_fixup}(\ensuremath{\mathit{u}})}$ runs in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time.

opendatastructures.org

Functions

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.

Functions

Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it.

See also the exhaustive reference chapter about JavaScript functions to get to know the details.

Defining functions

Function declarations

A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:

  • The name of the function.
  • A list of parameters to the function, enclosed in parentheses and separated by commas.
  • The JavaScript statements that define the function, enclosed in curly braces, { /* … */ }.

For example, the following code defines a function named square:

js
function square(number) {
  return number * number;
}

The function square takes one parameter, called number. The function consists of one statement that says to return the parameter of the function (that is, number) multiplied by itself. The return statement specifies the value returned by the function, which is number * number.

Parameters are essentially passed to functions by value — so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or in the code which called that function.

When you pass an object as a parameter, if the function changes the object's properties, that change is visible outside the function, as shown in the following example:

js
function myFunc(theObject) {
  theObject.make = "Toyota";
}

const myCar = {
  make: "Honda",
  model: "Accord",
  year: 1998,
};

console.log(myCar.make); // "Honda"
myFunc(myCar);
console.log(myCar.make); // "Toyota"

When you pass an array as a parameter, if the function changes any of the array's values, that change is visible outside the function, as shown in the following example:

js
function myFunc(theArr) {
  theArr[0] = 30;
}

const arr = [45];

console.log(arr[0]); // 45
myFunc(arr);
console.log(arr[0]); // 30

Function declarations and expressions can be nested, which forms a scope chain. For example:

js
function addSquares(a, b) {
  function square(x) {
    return x * x;
  }
  return square(a) + square(b);
}

See function scopes and closures for more information.

Function expressions

While the function declaration above is syntactically a statement, functions can also be created by a function expression.

Such a function can be anonymous; it does not have to have a name. For example, the function square could have been defined as:

js
const square = function (number) {
  return number * number;
};

console.log(square(4)); // 16

However, a name can be provided with a function expression. Providing a name allows the function to refer to itself, and also makes it easier to identify the function in a debugger's stack traces:

js
const factorial = function fac(n) {
  return n < 2 ? 1 : n * fac(n - 1);
};

console.log(factorial(3)); // 6

Function expressions are convenient when passing a function as an argument to another function. The following example defines a map function that should receive a function as first argument and an array as second argument. Then, it is called with a function defined by a function expression:

js
function map(f, a) {
  const result = new Array(a.length);
  for (let i = 0; i < a.length; i++) {
    result[i] = f(a[i]);
  }
  return result;
}

const numbers = [0, 1, 2, 5, 10];
const cubedNumbers = map(function (x) {
  return x * x * x;
}, numbers);
console.log(cubedNumbers); // [0, 1, 8, 125, 1000]

In JavaScript, a function can be defined based on a condition. For example, the following function definition defines myFunc only if num equals 0:

js
let myFunc;
if (num === 0) {
  myFunc = function (theObject) {
    theObject.make = "Toyota";
  };
}

In addition to defining functions as described here, you can also use the Function constructor to create functions from a string at runtime, much like eval().

A method is a function that is a property of an object. Read more about objects and methods in Working with objects.

Calling functions

Defining a function does not execute it. Defining it names the function and specifies what to do when the function is called.

Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square, you could call it as follows:

js
square(5);

The preceding statement calls the function with an argument of 5. The function executes its statements and returns the value 25.

Functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code). The scope of a function declaration is the function in which it is declared (or the entire program, if it is declared at the top level).

The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The showProps() function (defined in Working with objects) is an example of a function that takes an object as an argument.

A function can call itself. For example, here is a function that computes factorials recursively:

js
function factorial(n) {
  if (n === 0 || n === 1) {
    return 1;
  }
  return n * factorial(n - 1);
}

You could then compute the factorials of 1 through 5 as follows:

js
console.log(factorial(1)); // 1
console.log(factorial(2)); // 2
console.log(factorial(3)); // 6
console.log(factorial(4)); // 24
console.log(factorial(5)); // 120

There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime.

It turns out that functions are themselves objects — and in turn, these objects have methods. (See the Function object.) The call() and apply() methods can be used to achieve this goal.

Function hoisting

Consider the example below:

js
console.log(square(5)); // 25

function square(n) {
  return n * n;
}

This code runs without any error, despite the square() function being called before it's declared. This is because the JavaScript interpreter hoists the entire function declaration to the top of the current scope, so the code above is equivalent to:

js
// All function declarations are effectively at the top of the scope
function square(n) {
  return n * n;
}

console.log(square(5)); // 25

Function hoisting only works with function declarations — not with function expressions. The following code will not work:

js
console.log(square(5)); // ReferenceError: Cannot access 'square' before initialization
const square = function (n) {
  return n * n;
};

Recursion

A function can refer to and call itself. It can be referred to either by the function expression or declaration's name, or via any in-scope variable that refers to the function object. For example, consider the following function definition:

js
const foo = function bar() {
  // statements go here
};

Within the function body, you can refer to the function itself either as bar or foo, and call itself using bar() or foo().

A function that calls itself is called a recursive function. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case).

For example, consider the following loop:

js
let x = 0;
// "x < 10" is the loop condition
while (x < 10) {
  // do stuff
  x++;
}

It can be converted into a recursive function declaration, followed by a call to that function:

js
function loop(x) {
  // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
  if (x >= 10) {
    return;
  }
  // do stuff
  loop(x + 1); // the recursive call
}
loop(0);

However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (such as the DOM) is easier via recursion:

js
function walkTree(node) {
  if (node === null) {
    return;
  }
  // do something with node
  for (const child of node.childNodes) {
    walkTree(child);
  }
}

Compared to the function loop, each recursive call itself makes many recursive calls here.

It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often much more complex, and doing so requires the use of a stack.

In fact, recursion itself uses a stack: the function stack. The stack-like behavior can be seen in the following example:

js
function foo(i) {
  if (i < 0) {
    return;
  }
  console.log(`begin: ${i}`);
  foo(i - 1);
  console.log(`end: ${i}`);
}
foo(3);

// Logs:
// begin: 3
// begin: 2
// begin: 1
// begin: 0
// end: 0
// end: 1
// end: 2
// end: 3

Immediately Invoked Function Expressions (IIFE)

An Immediately Invoked Function Expression (IIFE) is a code pattern that directly calls a function defined as an expression. It looks like this:

js
(function () {
  // Do something
})();

const value = (function () {
  // Do something
  return someValue;
})();

Instead of saving the function in a variable, the function is immediately invoked. This is almost equivalent to just writing the function body, but there are a few unique benefits:

  • It creates an extra scope of variables, which helps to confine variables to the place where they are useful.
  • It is now an expression instead of a sequence of statements. This allows you to write complex computation logic when initializing variables.

For more information, see the IIFE glossary entry.

Function scopes and closures

Functions form a scope for variables—this means variables defined inside a function cannot be accessed from anywhere outside the function. The function scope inherits from all the upper scopes. For example, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access. On the other hand, the parent function (and any other parent scope) does not have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables in the inner function.

js
// The following variables are defined in the global scope
const num1 = 20;
const num2 = 3;
const name = "Chamakh";

// This function is defined in the global scope
function multiply() {
  return num1 * num2;
}

console.log(multiply()); // 60

// A nested function example
function getScore() {
  const num1 = 2;
  const num2 = 3;

  function add() {
    return `${name} scored ${num1 + num2}`;
  }

  return add();
}

console.log(getScore()); // "Chamakh scored 5"

Closures

We also refer to the function body as a closure. A closure is any piece of source code (most commonly, a function) that refers to some variables, and the closure "remembers" these variables even when the scope in which these variables were declared has exited.

Closures are usually illustrated with nested functions to show that they remember variables beyond the lifetime of its parent scope; but in fact, nested functions are unnecessary. Technically speaking, all functions in JavaScript form closures—some just don't capture anything, and closures don't even have to be functions. The key ingredients for a useful closure are the following:

  • A parent scope that defines some variables or functions. It should have a clear lifetime, which means it should finish execution at some point. Any scope that's not the global scope satisfies this requirement; this includes blocks, functions, modules, and more.
  • An inner scope defined within the parent scope, which refers to some variables or functions defined in the parent scope.
  • The inner scope manages to survive beyond the lifetime of the parent scope. For example, it is saved to a variable that's defined outside the parent scope, or it's returned from the parent scope (if the parent scope is a function).
  • Then, when you call the function outside of the parent scope, you can still access the variables or functions that were defined in the parent scope, even though the parent scope has finished execution.

The following is a typical example of a closure:

js
// The outer function defines a variable called "name"
const pet = function (name) {
  const getName = function () {
    // The inner function has access to the "name" variable of the outer function
    return name;
  };
  return getName; // Return the inner function, thereby exposing it to outer scopes
};
const myPet = pet("Vivie");

console.log(myPet()); // "Vivie"

It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.

js
const createPet = function (name) {
  let sex;

  const pet = {
    // setName(newName) is equivalent to setName: function (newName)
    // in this context
    setName(newName) {
      name = newName;
    },

    getName() {
      return name;
    },

    getSex() {
      return sex;
    },

    setSex(newSex) {
      if (
        typeof newSex === "string" &&
        (newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")
      ) {
        sex = newSex;
      }
    },
  };

  return pet;
};

const pet = createPet("Vivie");
console.log(pet.getName()); // Vivie

pet.setName("Oliver");
pet.setSex("male");
console.log(pet.getSex()); // male
console.log(pet.getName()); // Oliver

In the code above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent" and "encapsulated" data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.

js
const getCode = (function () {
  const apiCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify…

  return function () {
    return apiCode;
  };
})();

console.log(getCode()); // "0]Eal(eh&2"

In the code above, we use the IIFE pattern. Within this IIFE scope, two values exist: a variable apiCode and an unnamed function that gets returned and gets assigned to the variable getCode. apiCode is in the scope of the returned unnamed function but not in the scope of any other part of the program, so there is no way for reading the value of apiCode apart from via the getCode function.

Multiply-nested functions

Functions can be multiply-nested. For example:

  • A function (A) contains a function (B), which itself contains a function (C).
  • Both functions B and C form closures here. So, B can access A, and C can access B.
  • In addition, since C can access B which can access A, C can also access A.

Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining. Consider the following example:

js
function A(x) {
  function B(y) {
    function C(z) {
      console.log(x + y + z);
    }
    C(3);
  }
  B(2);
}
A(1); // Logs 6 (which is 1 + 2 + 3)

In this example, C accesses B's y and A's x. This can be done because:

  1. B forms a closure including A (i.e., B can access A's arguments and variables).
  2. C forms a closure including B.
  3. Because C's closure includes B and B's closure includes A, then C's closure also includes A. This means C can access both B and A's arguments and variables. In other words, C chains the scopes of B and A, in that order.

The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B.

Name conflicts

When two arguments or variables in the scopes of a closure have the same name, there is a name conflict. More nested scopes take precedence. So, the innermost scope takes the highest precedence, while the outermost scope takes the lowest. This is the scope chain. The first on the chain is the innermost scope, and the last is the outermost scope. Consider the following:

js
function outside() {
  const x = 5;
  function inside(x) {
    return x * 2;
  }
  return inside;
}

console.log(outside()(10)); // 20 (instead of 10)

The name conflict happens at the statement return x * 2 and is between inside's parameter x and outside's variable x. The scope chain here is inside => outside => global object. Therefore, inside's x takes precedences over outside's x, and 20 (inside's x) is returned instead of 10 (outside's x).

Using the arguments object

The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:

js
arguments[i];

where i is the ordinal number of the argument, starting at 0. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length.

Using the arguments object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object.

For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

js
function myConcat(separator) {
  let result = ""; // initialize list
  // iterate through arguments
  for (let i = 1; i < arguments.length; i++) {
    result += arguments[i] + separator;
  }
  return result;
}

You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

js
console.log(myConcat(", ", "red", "orange", "blue"));
// "red, orange, blue, "

console.log(myConcat("; ", "elephant", "giraffe", "lion", "cheetah"));
// "elephant; giraffe; lion; cheetah; "

console.log(myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"));
// "sage. basil. oregano. pepper. parsley. "

Note: The arguments variable is "array-like", but not an array. It is array-like in that it has a numbered index and a length property. However, it does not possess all of the array-manipulation methods.

See the Function object in the JavaScript reference for more information.

Function parameters

There are two special kinds of parameter syntax: default parameters and rest parameters.

Default parameters

In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value. This is exactly what default parameters do.

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined.

In the following example, if no value is provided for b, its value would be undefined when evaluating a*b, and a call to multiply would normally have returned NaN. However, this is prevented by the second line in this example:

js
function multiply(a, b) {
  b = typeof b !== "undefined" ? b : 1;
  return a * b;
}

console.log(multiply(5)); // 5

With default parameters, a manual check in the function body is no longer necessary. You can put 1 as the default value for b in the function head:

js
function multiply(a, b = 1) {
  return a * b;
}

console.log(multiply(5)); // 5

For more details, see default parameters in the reference.

Rest parameters

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

In the following example, the function multiply uses rest parameters to collect arguments from the second one to the end. The function then multiplies these by the first argument.

js
function multiply(multiplier, ...theArgs) {
  return theArgs.map((x) => multiplier * x);
}

const arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]

Arrow functions

An arrow function expression (also called a fat arrow to distinguish from a hypothetical -> syntax in future JavaScript) has a shorter syntax compared to function expressions and does not have its own this, arguments, super, or new.target. Arrow functions are always anonymous.

Two factors influenced the introduction of arrow functions: shorter functions and non-binding of this.

Shorter functions

In some functional patterns, shorter functions are welcome. Compare:

js
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = a.map(function (s) {
  return s.length;
});

console.log(a2); // [8, 6, 7, 9]

const a3 = a.map((s) => s.length);

console.log(a3); // [8, 6, 7, 9]

No separate this

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.

js
function Person() {
  // The Person() constructor defines `this` as itself.
  this.age = 0;

  setInterval(function growUp() {
    // In nonstrict mode, the growUp() function defines `this`
    // as the global object, which is different from the `this`
    // defined by the Person() constructor.
    this.age++;
  }, 1000);
}

const p = new Person();

In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.

js
function Person() {
  // Some choose `that` instead of `self`.
  // Choose one and be consistent.
  const self = this;
  self.age = 0;

  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    self.age++;
  }, 1000);
}

Alternatively, a bound function could be created so that the proper this value would be passed to the growUp() function.

An arrow function does not have its own this; the this value of the enclosing execution context is used. Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the enclosing function:

js
function Person() {
  this.age = 0;

  setInterval(() => {
    this.age++; // `this` properly refers to the person object
  }, 1000);
}

const p = new Person();

2.4. Populating a Table With Rows #

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

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

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

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

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

2.4. Populating a Table With Rows #

The INSERT statement is used to populate a table with rows:

INSERT INTO weather VALUES ('San Francisco', 46, 50, 0.25, '1994-11-27');

Note that all data types use rather obvious input formats. Constants that are not simple numeric values usually must be surrounded by single quotes ('), as in the example. The date type is actually quite flexible in what it accepts, but for this tutorial we will stick to the unambiguous format shown here.

The point type requires a coordinate pair as input, as shown here:

INSERT INTO cities VALUES ('San Francisco', '(-194.0, 53.0)');

The syntax used so far requires you to remember the order of the columns. An alternative syntax allows you to list the columns explicitly:

INSERT INTO weather (city, temp_lo, temp_hi, prcp, date)
    VALUES ('San Francisco', 43, 57, 0.0, '1994-11-29');

You can list the columns in a different order if you wish or even omit some columns, e.g., if the precipitation is unknown:

INSERT INTO weather (date, city, temp_hi, temp_lo)
    VALUES ('1994-11-29', 'Hayward', 54, 37);

Many developers consider explicitly listing the columns better style than relying on the order implicitly.

Please enter all the commands shown above so you have some data to work with in the following sections.

You could also have used COPY to load large amounts of data from flat-text files. This is usually faster because the COPY command is optimized for this application while allowing less flexibility than INSERT. An example would be:

COPY weather FROM '/home/user/weather.txt';

where the file name for the source file must be available on the machine running the backend process, not the client, since the backend process reads the file directly. The data inserted above into the weather table could also be inserted from a file containing (values are separated by a tab character):

San Francisco    46    50    0.25    1994-11-27
San Francisco    43    57    0.0    1994-11-29
Hayward    37    54    \N    1994-11-29

You can read more about the COPY command in COPY.

25.1. SQL Dump #

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.

25.1. SQL Dump #

The idea behind this dump method is to generate a file with SQL commands that, when fed back to the server, will recreate the database in the same state as it was at the time of the dump. PostgreSQL provides the utility program pg_dump for this purpose. The basic usage of this command is:

pg_dump dbname > dumpfile

As you see, pg_dump writes its result to the standard output. We will see below how this can be useful. While the above command creates a text file, pg_dump can create files in other formats that allow for parallelism and more fine-grained control of object restoration.

pg_dump is a regular PostgreSQL client application (albeit a particularly clever one). This means that you can perform this backup procedure from any remote host that has access to the database. But remember that pg_dump does not operate with special permissions. In particular, it must have read access to all tables that you want to back up, so in order to back up the entire database you almost always have to run it as a database superuser. (If you do not have sufficient privileges to back up the entire database, you can still back up portions of the database to which you do have access using options such as -n schema or -t table.)

To specify which database server pg_dump should contact, use the command line options -h host and -p port. The default host is the local host or whatever your PGHOST environment variable specifies. Similarly, the default port is indicated by the PGPORT environment variable or, failing that, by the compiled-in default. (Conveniently, the server will normally have the same compiled-in default.)

Like any other PostgreSQL client application, pg_dump will by default connect with the database user name that is equal to the current operating system user name. To override this, either specify the -U option or set the environment variable PGUSER. Remember that pg_dump connections are subject to the normal client authentication mechanisms (which are described in Chapter 20).

An important advantage of pg_dump over the other backup methods described later is that pg_dump's output can generally be re-loaded into newer versions of PostgreSQL, whereas file-level backups and continuous archiving are both extremely server-version-specific. pg_dump is also the only method that will work when transferring a database to a different machine architecture, such as going from a 32-bit to a 64-bit server.

Dumps created by pg_dump are internally consistent, meaning, the dump represents a snapshot of the database at the time pg_dump began running. pg_dump does not block other operations on the database while it is working. (Exceptions are those operations that need to operate with an exclusive lock, such as most forms of ALTER TABLE.)

25.1.1. Restoring the Dump #

Text files created by pg_dump are intended to be read by the psql program using its default settings. The general command form to restore a text dump is

psql -X dbname < dumpfile

where dumpfile is the file output by the pg_dump command. The database dbname will not be created by this command, so you must create it yourself from template0 before executing psql (e.g., with createdb -T template0 dbname). To ensure psql runs with its default settings, use the -X (--no-psqlrc) option. psql supports options similar to pg_dump for specifying the database server to connect to and the user name to use. See the psql reference page for more information.

Non-text file dumps should be restored using the pg_restore utility.

Before restoring an SQL dump, all the users who own objects or were granted permissions on objects in the dumped database must already exist. If they do not, the restore will fail to recreate the objects with the original ownership and/or permissions. (Sometimes this is what you want, but usually it is not.)

By default, the psql script will continue to execute after an SQL error is encountered. You might wish to run psql with the ON_ERROR_STOP variable set to alter that behavior and have psql exit with an exit status of 3 if an SQL error occurs:

psql -X --set ON_ERROR_STOP=on dbname < dumpfile

Either way, you will only have a partially restored database. Alternatively, you can specify that the whole dump should be restored as a single transaction, so the restore is either fully completed or fully rolled back. This mode can be specified by passing the -1 or --single-transaction command-line options to psql. When using this mode, be aware that even a minor error can rollback a restore that has already run for many hours. However, that might still be preferable to manually cleaning up a complex database after a partially restored dump.

The ability of pg_dump and psql to write to or read from pipes makes it possible to dump a database directly from one server to another, for example:

pg_dump -h host1 dbname | psql -X -h host2 dbname

Important

The dumps produced by pg_dump are relative to template0. This means that any languages, procedures, etc. added via template1 will also be dumped by pg_dump. As a result, when restoring, if you are using a customized template1, you must create the empty database from template0, as in the example above.

After restoring a backup, it is wise to run ANALYZE on each database so the query optimizer has useful statistics; see Section 24.1.3 and Section 24.1.6 for more information. For more advice on how to load large amounts of data into PostgreSQL efficiently, refer to Section 14.4.

25.1.2. Using pg_dumpall #

pg_dump dumps only a single database at a time, and it does not dump information about roles or tablespaces (because those are cluster-wide rather than per-database). To support convenient dumping of the entire contents of a database cluster, the pg_dumpall program is provided. pg_dumpall backs up each database in a given cluster, and also preserves cluster-wide data such as role and tablespace definitions. The basic usage of this command is:

pg_dumpall > dumpfile

The resulting dump can be restored with psql:

psql -X -f dumpfile postgres

(Actually, you can specify any existing database name to start from, but if you are loading into an empty cluster then postgres should usually be used.) It is always necessary to have database superuser access when restoring a pg_dumpall dump, as that is required to restore the role and tablespace information. If you use tablespaces, make sure that the tablespace paths in the dump are appropriate for the new installation.

pg_dumpall works by emitting commands to re-create roles, tablespaces, and empty databases, then invoking pg_dump for each database. This means that while each database will be internally consistent, the snapshots of different databases are not synchronized.

Cluster-wide data can be dumped alone using the pg_dumpall --globals-only option. This is necessary to fully backup the cluster if running the pg_dump command on individual databases.

25.1.3. Handling Large Databases #

Some operating systems have maximum file size limits that cause problems when creating large pg_dump output files. Fortunately, pg_dump can write to the standard output, so you can use standard Unix tools to work around this potential problem. There are several possible methods:

Use compressed dumps.  You can use your favorite compression program, for example gzip:

pg_dump dbname | gzip > filename.gz

Reload with:

gunzip -c filename.gz | psql dbname

or:

cat filename.gz | gunzip | psql dbname

Use split.  The split command allows you to split the output into smaller files that are acceptable in size to the underlying file system. For example, to make 2 gigabyte chunks:

pg_dump dbname | split -b 2G - filename

Reload with:

cat filename* | psql dbname

If using GNU split, it is possible to use it and gzip together:

pg_dump dbname | split -b 2G --filter='gzip > $FILE.gz'

It can be restored using zcat.

Use pg_dump's custom dump format.  If PostgreSQL was built on a system with the zlib compression library installed, the custom dump format will compress data as it writes it to the output file. This will produce dump file sizes similar to using gzip, but it has the added advantage that tables can be restored selectively. The following command dumps a database using the custom dump format:

pg_dump -Fc dbname > filename

A custom-format dump is not a script for psql, but instead must be restored with pg_restore, for example:

pg_restore -d dbname filename

See the pg_dump and pg_restore reference pages for details.

For very large databases, you might need to combine split with one of the other two approaches.

Use pg_dump's parallel dump feature.  To speed up the dump of a large database, you can use pg_dump's parallel mode. This will dump multiple tables at the same time. You can control the degree of parallelism with the -j parameter. Parallel dumps are only supported for the "directory" archive format.

pg_dump -j num -F d -f out.dir dbname

You can use pg_restore -j to restore a dump in parallel. This will work for any archive of either the "custom" or the "directory" archive mode, whether or not it has been created with pg_dump -j.

22.6. Random Variables 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.6. Random Variables
Open the notebook in SageMaker Studio Lab

In Section 2.6 we saw the basics of how to work with discrete random variables, which in our case refer to those random variables which take either a finite set of possible values, or the integers. In this section, we develop the theory of continuous random variables, which are random variables which can take on any real value.

22.6.1. Continuous Random Variables

Continuous random variables are a significantly more subtle topic than discrete random variables. A fair analogy to make is that the technical jump is comparable to the jump between adding lists of numbers and integrating functions. As such, we will need to take some time to develop the theory.

22.6.1.1. From Discrete to Continuous

To understand the additional technical challenges encountered when working with continuous random variables, let’s perform a thought experiment. Suppose that we are throwing a dart at the dart board, and we want to know the probability that it hits exactly \(2 \textrm{cm}\) from the center of the board.

To start with, we imagine measuring a single digit of accuracy, that is to say with bins for \(0 \textrm{cm}\), \(1 \textrm{cm}\), \(2 \textrm{cm}\), and so on. We throw say \(100\) darts at the dart board, and if \(20\) of them fall into the bin for \(2\textrm{cm}\) we conclude that \(20\%\) of the darts we throw hit the board \(2 \textrm{cm}\) away from the center.

However, when we look closer, this does not match our question! We wanted exact equality, whereas these bins hold all that fell between say \(1.5\textrm{cm}\) and \(2.5\textrm{cm}\).

Undeterred, we continue further. We measure even more precisely, say \(1.9\textrm{cm}\), \(2.0\textrm{cm}\), \(2.1\textrm{cm}\), and now see that perhaps \(3\) of the \(100\) darts hit the board in the \(2.0\textrm{cm}\) bucket. Thus we conclude the probability is \(3\%\).

However, this does not solve anything! We have just pushed the issue down one digit further. Let’s abstract a bit. Imagine we know the probability that the first \(k\) digits match with \(2.00000\ldots\) and we want to know the probability it matches for the first \(k+1\) digits. It is fairly reasonable to assume that the \({k+1}^{\textrm{th}}\) digit is essentially a random choice from the set \(\{0, 1, 2, \ldots, 9\}\). At least, we cannot conceive of a physically meaningful process which would force the number of micrometers away form the center to prefer to end in a \(7\) vs a \(3\).

What this means is that in essence each additional digit of accuracy we require should decrease probability of matching by a factor of \(10\). Or put another way, we would expect that

(22.6.1)\[P(\textrm{distance is}\; 2.00\ldots, \;\textrm{to}\; k \;\textrm{digits} ) \approx p\cdot10^{-k}.\]

The value \(p\) essentially encodes what happens with the first few digits, and the \(10^{-k}\) handles the rest.

Notice that if we know the position accurate to \(k=4\) digits after the decimal, that means we know the value falls within the interval say \([1.99995,2.00005]\) which is an interval of length \(2.00005-1.99995 = 10^{-4}\). Thus, if we call the length of this interval \(\epsilon\), we can say

(22.6.2)\[P(\textrm{distance is in an}\; \epsilon\textrm{-sized interval around}\; 2 ) \approx \epsilon \cdot p.\]

Let’s take this one final step further. We have been thinking about the point \(2\) the entire time, but never thinking about other points. Nothing is different there fundamentally, but it is the case that the value \(p\) will likely be different. We would at least hope that a dart thrower was more likely to hit a point near the center, like \(2\textrm{cm}\) rather than \(20\textrm{cm}\). Thus, the value \(p\) is not fixed, but rather should depend on the point \(x\). This tells us that we should expect

(22.6.3)\[P(\textrm{distance is in an}\; \epsilon \textrm{-sized interval around}\; x ) \approx \epsilon \cdot p(x).\]

Indeed, (22.6.3) precisely defines the probability density function. It is a function \(p(x)\) which encodes the relative probability of hitting near one point vs. another. Let’s visualize what such a function might look like.

%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 the probability density function for some random variable
x = torch.arange(-5, 5, 0.01)
p = 0.2*torch.exp(-(x - 3)**2 / 2)/torch.sqrt(2 * torch.tensor(torch.pi)) + \
    0.8*torch.exp(-(x + 1)**2 / 2)/torch.sqrt(2 * torch.tensor(torch.pi))

d2l.plot(x, p, 'x', 'Density')
../_images/output_random-variables_886f4c_3_0.svg

The locations where the function value is large indicates regions where we are more likely to find the random value. The low portions are areas where we are unlikely to find the random value.

22.6.1.2. Probability Density Functions

Let’s now investigate this further. We have already seen what a probability density function is intuitively for a random variable \(X\), namely the density function is a function \(p(x)\) so that

(22.6.4)\[P(X \; \textrm{is in an}\; \epsilon \textrm{-sized interval around}\; x ) \approx \epsilon \cdot p(x).\]

But what does this imply for the properties of \(p(x)\)?

First, probabilities are never negative, thus we should expect that \(p(x) \ge 0\) as well.

Second, let’s imagine that we slice up the \(\mathbb{R}\) into an infinite number of slices which are \(\epsilon\) wide, say with slices \((\epsilon\cdot i, \epsilon \cdot (i+1)]\). For each of these, we know from (22.6.4) the probability is approximately

(22.6.5)\[P(X \; \textrm{is in an}\; \epsilon\textrm{-sized interval around}\; x ) \approx \epsilon \cdot p(\epsilon \cdot i),\]

so summed over all of them it should be

(22.6.6)\[P(X\in\mathbb{R}) \approx \sum_i \epsilon \cdot p(\epsilon\cdot i).\]

This is nothing more than the approximation of an integral discussed in Section 22.5, thus we can say that

(22.6.7)\[P(X\in\mathbb{R}) = \int_{-\infty}^{\infty} p(x) \; dx.\]

We know that \(P(X\in\mathbb{R}) = 1\), since the random variable must take on some number, we can conclude that for any density

(22.6.8)\[\int_{-\infty}^{\infty} p(x) \; dx = 1.\]

Indeed, digging into this further shows that for any \(a\), and \(b\), we see that

(22.6.9)\[P(X\in(a, b]) = \int _ {a}^{b} p(x) \; dx.\]

We may approximate this in code by using the same discrete approximation methods as before. In this case we can approximate the probability of falling in the blue region.

# Approximate probability using numerical integration
epsilon = 0.01
x = torch.arange(-5, 5, 0.01)
p = 0.2*torch.exp(-(x - 3)**2 / 2) / torch.sqrt(2 * torch.tensor(torch.pi)) +\
    0.8*torch.exp(-(x + 1)**2 / 2) / torch.sqrt(2 * torch.tensor(torch.pi))

d2l.set_figsize()
d2l.plt.plot(x, p, color='black')
d2l.plt.fill_between(x.tolist()[300:800], p.tolist()[300:800])
d2l.plt.show()

f'approximate Probability: {torch.sum(epsilon*p[300:800])}'
../_images/output_random-variables_886f4c_15_0.svg
'approximate Probability: 0.773617148399353'

It turns out that these two properties describe exactly the space of possible probability density functions (or p.d.f.’s for the commonly encountered abbreviation). They are non-negative functions \(p(x) \ge 0\) such that

(22.6.10)\[\int_{-\infty}^{\infty} p(x) \; dx = 1.\]

We interpret this function by using integration to obtain the probability our random variable is in a specific interval:

(22.6.11)\[P(X\in(a, b]) = \int _ {a}^{b} p(x) \; dx.\]

In Section 22.8 we will see a number of common distributions, but let’s continue working in the abstract.

22.6.1.3. Cumulative Distribution Functions

In the previous section, we saw the notion of the p.d.f. In practice, this is a commonly encountered method to discuss continuous random variables, but it has one significant pitfall: that the values of the p.d.f. are not themselves probabilities, but rather a function that we must integrate to yield probabilities. There is nothing wrong with a density being larger than \(10\), as long as it is not larger than \(10\) for more than an interval of length \(1/10\). This can be counter-intuitive, so people often also think in terms of the cumulative distribution function, or c.d.f., which is a probability.

In particular, by using (22.6.11), we define the c.d.f. for a random variable \(X\) with density \(p(x)\) by

(22.6.12)\[F(x) = \int _ {-\infty}^{x} p(x) \; dx = P(X \le x).\]

Let’s observe a few properties.

  • \(F(x) \rightarrow 0\) as \(x\rightarrow -\infty\).

  • \(F(x) \rightarrow 1\) as \(x\rightarrow \infty\).

  • \(F(x)\) is non-decreasing (\(y > x \implies F(y) \ge F(x)\)).

  • \(F(x)\) is continuous (has no jumps) if \(X\) is a continuous random variable.

With the fourth bullet point, note that this would not be true if \(X\) were discrete, say taking the values \(0\) and \(1\) both with probability \(1/2\). In that case

(22.6.13)\[\begin{split}F(x) = \begin{cases} 0 & x < 0, \\ \frac{1}{2} & x < 1, \\ 1 & x \ge 1. \end{cases}\end{split}\]

In this example, we see one of the benefits of working with the c.d.f., the ability to deal with continuous or discrete random variables in the same framework, or indeed mixtures of the two (flip a coin: if heads return the roll of a die, if tails return the distance of a dart throw from the center of a dart board).

22.6.1.4. Means

Suppose that we are dealing with a random variables \(X\). The distribution itself can be hard to interpret. It is often useful to be able to summarize the behavior of a random variable concisely. Numbers that help us capture the behavior of a random variable are called summary statistics. The most commonly encountered ones are the mean, the variance, and the standard deviation.

The mean encodes the average value of a random variable. If we have a discrete random variable \(X\), which takes the values \(x_i\) with probabilities \(p_i\), then the mean is given by the weighted average: sum the values times the probability that the random variable takes on that value:

(22.6.14)\[\mu_X = E[X] = \sum_i x_i p_i.\]

The way we should interpret the mean (albeit with caution) is that it tells us essentially where the random variable tends to be located.

As a minimalistic example that we will examine throughout this section, let’s take \(X\) to be the random variable which takes the value \(a-2\) with probability \(p\), \(a+2\) with probability \(p\) and \(a\) with probability \(1-2p\). We can compute using (22.6.14) that, for any possible choice of \(a\) and \(p\), the mean is

(22.6.15)\[\mu_X = E[X] = \sum_i x_i p_i = (a-2)p + a(1-2p) + (a+2)p = a.\]

Thus we see that the mean is \(a\). This matches the intuition since \(a\) is the location around which we centered our random variable.

Because they are helpful, let’s summarize a few properties.

  • For any random variable \(X\) and numbers \(a\) and \(b\), we have that \(\mu_{aX+b} = a\mu_X + b\).

  • If we have two random variables \(X\) and \(Y\), we have \(\mu_{X+Y} = \mu_X+\mu_Y\).

Means are useful for understanding the average behavior of a random variable, however the mean is not sufficient to even have a full intuitive understanding. Making a profit of \(\$10 \pm \$1\) per sale is very different from making \(\$10 \pm \$15\) per sale despite having the same average value. The second one has a much larger degree of fluctuation, and thus represents a much larger risk. Thus, to understand the behavior of a random variable, we will need at minimum one more measure: some measure of how widely a random variable fluctuates.

22.6.1.5. Variances

This leads us to consider the variance of a random variable. This is a quantitative measure of how far a random variable deviates from the mean. Consider the expression \(X - \mu_X\). This is the deviation of the random variable from its mean. This value can be positive or negative, so we need to do something to make it positive so that we are measuring the magnitude of the deviation.

A reasonable thing to try is to look at \(\left|X-\mu_X\right|\), and indeed this leads to a useful quantity called the mean absolute deviation, however due to connections with other areas of mathematics and statistics, people often use a different solution.

In particular, they look at \((X-\mu_X)^2.\) If we look at the typical size of this quantity by taking the mean, we arrive at the variance

(22.6.16)\[\sigma_X^2 = \textrm{Var}(X) = E\left[(X-\mu_X)^2\right] = E[X^2] - \mu_X^2.\]

The last equality in (22.6.16) holds by expanding out the definition in the middle, and applying the properties of expectation.

Let’s look at our example where \(X\) is the random variable which takes the value \(a-2\) with probability \(p\), \(a+2\) with probability \(p\) and \(a\) with probability \(1-2p\). In this case \(\mu_X = a\), so all we need to compute is \(E\left[X^2\right]\). This can readily be done:

(22.6.17)\[E\left[X^2\right] = (a-2)^2p + a^2(1-2p) + (a+2)^2p = a^2 + 8p.\]

Thus, we see that by (22.6.16) our variance is

(22.6.18)\[\sigma_X^2 = \textrm{Var}(X) = E[X^2] - \mu_X^2 = a^2 + 8p - a^2 = 8p.\]

This result again makes sense. The largest \(p\) can be is \(1/2\) which corresponds to picking \(a-2\) or \(a+2\) with a coin flip. The variance of this being \(4\) corresponds to the fact that both \(a-2\) and \(a+2\) are \(2\) units away from the mean, and \(2^2 = 4\). On the other end of the spectrum, if \(p=0\), this random variable always takes the value \(0\) and so it has no variance at all.

We will list a few properties of variance below:

  • For any random variable \(X\), \(\textrm{Var}(X) \ge 0\), with \(\textrm{Var}(X) = 0\) if and only if \(X\) is a constant.

  • For any random variable \(X\) and numbers \(a\) and \(b\), we have that \(\textrm{Var}(aX+b) = a^2\textrm{Var}(X)\).

  • If we have two independent random variables \(X\) and \(Y\), we have \(\textrm{Var}(X+Y) = \textrm{Var}(X) + \textrm{Var}(Y)\).

When interpreting these values, there can be a bit of a hiccup. In particular, let’s try imagining what happens if we keep track of units through this computation. Suppose that we are working with the star rating assigned to a product on the web page. Then \(a\), \(a-2\), and \(a+2\) are all measured in units of stars. Similarly, the mean \(\mu_X\) is then also measured in stars (being a weighted average). However, if we get to the variance, we immediately encounter an issue, which is we want to look at \((X-\mu_X)^2\), which is in units of squared stars. This means that the variance itself is not comparable to the original measurements. To make it interpretable, we will need to return to our original units.

22.6.1.6. Standard Deviations

This summary statistics can always be deduced from the variance by taking the square root! Thus we define the standard deviation to be

(22.6.19)\[\sigma_X = \sqrt{\textrm{Var}(X)}.\]

In our example, this means we now have the standard deviation is \(\sigma_X = 2\sqrt{2p}\). If we are dealing with units of stars for our review example, \(\sigma_X\) is again in units of stars.

The properties we had for the variance can be restated for the standard deviation.

  • For any random variable \(X\), \(\sigma_{X} \ge 0\).

  • For any random variable \(X\) and numbers \(a\) and \(b\), we have that \(\sigma_{aX+b} = |a|\sigma_{X}\)

  • If we have two independent random variables \(X\) and \(Y\), we have \(\sigma_{X+Y} = \sqrt{\sigma_{X}^2 + \sigma_{Y}^2}\).

It is natural at this moment to ask, “If the standard deviation is in the units of our original random variable, does it represent something we can draw with regards to that random variable?” The answer is a resounding yes! Indeed much like the mean told us the typical location of our random variable, the standard deviation gives the typical range of variation of that random variable. We can make this rigorous with what is known as Chebyshev’s inequality:

(22.6.20)\[P\left(X \not\in [\mu_X - \alpha\sigma_X, \mu_X + \alpha\sigma_X]\right) \le \frac{1}{\alpha^2}.\]

Or to state it verbally in the case of \(\alpha=10\), \(99\%\) of the samples from any random variable fall within \(10\) standard deviations of the mean. This gives an immediate interpretation to our standard summary statistics.

To see how this statement is rather subtle, let’s take a look at our running example again where \(X\) is the random variable which takes the value \(a-2\) with probability \(p\), \(a+2\) with probability \(p\) and \(a\) with probability \(1-2p\). We saw that the mean was \(a\) and the standard deviation was \(2\sqrt{2p}\). This means, if we take Chebyshev’s inequality (22.6.20) with \(\alpha = 2\), we see that the expression is

(22.6.21)\[P\left(X \not\in [a - 4\sqrt{2p}, a + 4\sqrt{2p}]\right) \le \frac{1}{4}.\]

This means that \(75\%\) of the time, this random variable will fall within this interval for any value of \(p\). Now, notice that as \(p \rightarrow 0\), this interval also converges to the single point \(a\). But we know that our random variable takes the values \(a-2, a\), and \(a+2\) only so eventually we can be certain \(a-2\) and \(a+2\) will fall outside the interval! The question is, at what \(p\) does that happen. So we want to solve: for what \(p\) does \(a+4\sqrt{2p} = a+2\), which is solved when \(p=1/8\), which is exactly the first \(p\) where it could possibly happen without violating our claim that no more than \(1/4\) of samples from the distribution would fall outside the interval (\(1/8\) to the left, and \(1/8\) to the right).

Let’s visualize this. We will show the probability of getting the three values as three vertical bars with height proportional to the probability. The interval will be drawn as a horizontal line in the middle. The first plot shows what happens for \(p > 1/8\) where the interval safely contains all points.

# Define a helper to plot these figures
def plot_chebyshev(a, p):
    d2l.set_figsize()
    d2l.plt.stem([a-2, a, a+2], [p, 1-2*p, p], use_line_collection=True)
    d2l.plt.xlim([-4, 4])
    d2l.plt.xlabel('x')
    d2l.plt.ylabel('p.m.f.')

    d2l.plt.hlines(0.5, a - 4 * torch.sqrt(2 * p),
                   a + 4 * torch.sqrt(2 * p), 'black', lw=4)
    d2l.plt.vlines(a - 4 * torch.sqrt(2 * p), 0.53, 0.47, 'black', lw=1)
    d2l.plt.vlines(a + 4 * torch.sqrt(2 * p), 0.53, 0.47, 'black', lw=1)
    d2l.plt.title(f'p = {p:.3f}')

    d2l.plt.show()

# Plot interval when p > 1/8
plot_chebyshev(0.0, torch.tensor(0.2))
../_images/output_random-variables_886f4c_27_0.svg

The second shows that at \(p = 1/8\), the interval exactly touches the two points. This shows that the inequality is sharp, since no smaller interval could be taken while keeping the inequality true.

# Plot interval when p = 1/8
plot_chebyshev(0.0, torch.tensor(0.125))
../_images/output_random-variables_886f4c_39_0.svg

The third shows that for \(p < 1/8\) the interval only contains the center. This does not invalidate the inequality since we only needed to ensure that no more than \(1/4\) of the probability falls outside the interval, which means that once \(p < 1/8\), the two points at \(a-2\) and \(a+2\) can be discarded.

# Plot interval when p < 1/8
plot_chebyshev(0.0, torch.tensor(0.05))
../_images/output_random-variables_886f4c_51_0.svg

22.6.1.7. Means and Variances in the Continuum

This has all been in terms of discrete random variables, but the case of continuous random variables is similar. To intuitively understand how this works, imagine that we split the real number line into intervals of length \(\epsilon\) given by \((\epsilon i, \epsilon (i+1)]\). Once we do this, our continuous random variable has been made discrete and we can use (22.6.14) say that

(22.6.22)\[\begin{split}\begin{aligned} \mu_X & \approx \sum_{i} (\epsilon i)P(X \in (\epsilon i, \epsilon (i+1)]) \\ & \approx \sum_{i} (\epsilon i)p_X(\epsilon i)\epsilon, \\ \end{aligned}\end{split}\]

where \(p_X\) is the density of \(X\). This is an approximation to the integral of \(xp_X(x)\), so we can conclude that

(22.6.23)\[\mu_X = \int_{-\infty}^\infty xp_X(x) \; dx.\]

Similarly, using (22.6.16) the variance can be written as

(22.6.24)\[\sigma^2_X = E[X^2] - \mu_X^2 = \int_{-\infty}^\infty x^2p_X(x) \; dx - \left(\int_{-\infty}^\infty xp_X(x) \; dx\right)^2.\]

Everything stated above about the mean, the variance, and the standard deviation still applies in this case. For instance, if we consider the random variable with density

(22.6.25)\[\begin{split}p(x) = \begin{cases} 1 & x \in [0,1], \\ 0 & \textrm{otherwise}. \end{cases}\end{split}\]

we can compute

(22.6.26)\[\mu_X = \int_{-\infty}^\infty xp(x) \; dx = \int_0^1 x \; dx = \frac{1}{2}.\]

and

(22.6.27)\[\sigma_X^2 = \int_{-\infty}^\infty x^2p(x) \; dx - \left(\frac{1}{2}\right)^2 = \frac{1}{3} - \frac{1}{4} = \frac{1}{12}.\]

As a warning, let’s examine one more example, known as the Cauchy distribution. This is the distribution with p.d.f. given by

(22.6.28)\[p(x) = \frac{1}{1+x^2}.\]
# Plot the Cauchy distribution p.d.f.
x = torch.arange(-5, 5, 0.01)
p = 1 / (1 + x**2)

d2l.plot(x, p, 'x', 'p.d.f.')
../_images/output_random-variables_886f4c_63_0.svg

This function looks innocent, and indeed consulting a table of integrals will show it has area one under it, and thus it defines a continuous random variable.

To see what goes astray, let’s try to compute the variance of this. This would involve using (22.6.16) computing

(22.6.29)\[\int_{-\infty}^\infty \frac{x^2}{1+x^2}\; dx.\]

The function on the inside looks like this:

# Plot the integrand needed to compute the variance
x = torch.arange(-20, 20, 0.01)
p = x**2 / (1 + x**2)

d2l.plot(x, p, 'x', 'integrand')
../_images/output_random-variables_886f4c_75_0.svg

This function clearly has infinite area under it since it is essentially the constant one with a small dip near zero, and indeed we could show that

(22.6.30)\[\int_{-\infty}^\infty \frac{x^2}{1+x^2}\; dx = \infty.\]

This means it does not have a well-defined finite variance.

However, looking deeper shows an even more disturbing result. Let’s try to compute the mean using (22.6.14). Using the change of variables formula, we see

(22.6.31)\[\mu_X = \int_{-\infty}^{\infty} \frac{x}{1+x^2} \; dx = \frac{1}{2}\int_1^\infty \frac{1}{u} \; du.\]

The integral inside is the definition of the logarithm, so this is in essence \(\log(\infty) = \infty\), so there is no well-defined average value either!

Machine learning scientists define their models so that we most often do not need to deal with these issues, and will in the vast majority of cases deal with random variables with well-defined means and variances. However, every so often random variables with heavy tails (that is those random variables where the probabilities of getting large values are large enough to make things like the mean or variance undefined) are helpful in modeling physical systems, thus it is worth knowing that they exist.

22.6.1.8. Joint Density Functions

The above work all assumes we are working with a single real valued random variable. But what if we are dealing with two or more potentially highly correlated random variables? This circumstance is the norm in machine learning: imagine random variables like \(R_{i, j}\) which encode the red value of the pixel at the \((i, j)\) coordinate in an image, or \(P_t\) which is a random variable given by a stock price at time \(t\). Nearby pixels tend to have similar color, and nearby times tend to have similar prices. We cannot treat them as separate random variables, and expect to create a successful model (we will see in Section 22.9 a model that under-performs due to such an assumption). We need to develop the mathematical language to handle these correlated continuous random variables.

Thankfully, with the multiple integrals in Section 22.5 we can develop such a language. Suppose that we have, for simplicity, two random variables \(X, Y\) which can be correlated. Then, similar to the case of a single variable, we can ask the question:

(22.6.32)\[P(X \;\textrm{is in an}\; \epsilon \textrm{-sized interval around}\; x \; \textrm{and} \;Y \;\textrm{is in an}\; \epsilon \textrm{-sized interval around}\; y ).\]

Similar reasoning to the single variable case shows that this should be approximately

(22.6.33)\[P(X \;\textrm{is in an}\; \epsilon \textrm{-sized interval around}\; x \; \textrm{and} \;Y \;\textrm{is in an}\; \epsilon \textrm{-sized interval around}\; y ) \approx \epsilon^{2}p(x, y),\]

for some function \(p(x, y)\). This is referred to as the joint density of \(X\) and \(Y\). Similar properties are true for this as we saw in the single variable case. Namely:

  • \(p(x, y) \ge 0\);

  • \(\int _ {\mathbb{R}^2} p(x, y) \;dx \;dy = 1\);

  • \(P((X, Y) \in \mathcal{D}) = \int _ {\mathcal{D}} p(x, y) \;dx \;dy\).

In this way, we can deal with multiple, potentially correlated random variables. If we wish to work with more than two random variables, we can extend the multivariate density to as many coordinates as desired by considering \(p(\mathbf{x}) = p(x_1, \ldots, x_n)\). The same properties of being non-negative, and having total integral of one still hold.

22.6.1.9. Marginal Distributions

When dealing with multiple variables, we oftentimes want to be able to ignore the relationships and ask, “how is this one variable distributed?” Such a distribution is called a marginal distribution.

To be concrete, let’s suppose that we have two random variables \(X, Y\) with joint density given by \(p _ {X, Y}(x, y)\). We will be using the subscript to indicate what random variables the density is for. The question of finding the marginal distribution is taking this function, and using it to find \(p _ X(x)\).

As with most things, it is best to return to the intuitive picture to figure out what should be true. Recall that the density is the function \(p _ X\) so that

(22.6.34)\[P(X \in [x, x+\epsilon]) \approx \epsilon \cdot p _ X(x).\]

There is no mention of \(Y\), but if all we are given is \(p _{X, Y}\), we need to include \(Y\) somehow. We can first observe that this is the same as

(22.6.35)\[P(X \in [x, x+\epsilon] \textrm{, and } Y \in \mathbb{R}) \approx \epsilon \cdot p _ X(x).\]

Our density does not directly tell us about what happens in this case, we need to split into small intervals in \(y\) as well, so we can write this as

(22.6.36)\[\begin{split}\begin{aligned} \epsilon \cdot p _ X(x) & \approx \sum _ {i} P(X \in [x, x+\epsilon] \textrm{, and } Y \in [\epsilon \cdot i, \epsilon \cdot (i+1)]) \\ & \approx \sum _ {i} \epsilon^{2} p _ {X, Y}(x, \epsilon\cdot i). \end{aligned}\end{split}\]
../_images/marginal.svg

Fig. 22.6.1 By summing along the columns of our array of probabilities, we are able to obtain the marginal distribution for just the random variable represented along the \(\mathit{x}\)-axis.

This tells us to add up the value of the density along a series of squares in a line as is shown in Fig. 22.6.1. Indeed, after canceling one factor of epsilon from both sides, and recognizing the sum on the right is the integral over \(y\), we can conclude that

(22.6.37)\[\begin{split}\begin{aligned} p _ X(x) & \approx \sum _ {i} \epsilon p _ {X, Y}(x, \epsilon\cdot i) \\ & \approx \int_{-\infty}^\infty p_{X, Y}(x, y) \; dy. \end{aligned}\end{split}\]

Thus we see

(22.6.38)\[p _ X(x) = \int_{-\infty}^\infty p_{X, Y}(x, y) \; dy.\]

This tells us that to get a marginal distribution, we integrate over the variables we do not care about. This process is often referred to as integrating out or marginalized out the unneeded variables.

22.6.1.10. Covariance

When dealing with multiple random variables, there is one additional summary statistic which is helpful to know: the covariance. This measures the degree that two random variable fluctuate together.

Suppose that we have two random variables \(X\) and \(Y\), to begin with, let’s suppose they are discrete, taking on values \((x_i, y_j)\) with probability \(p_{ij}\). In this case, the covariance is defined as

(22.6.39)\[\sigma_{XY} = \textrm{Cov}(X, Y) = \sum_{i, j} (x_i - \mu_X) (y_j-\mu_Y) p_{ij}. = E[XY] - E[X]E[Y].\]

To think about this intuitively: consider the following pair of random variables. Suppose that \(X\) takes the values \(1\) and \(3\), and \(Y\) takes the values \(-1\) and \(3\). Suppose that we have the following probabilities

(22.6.40)\[\begin{split}\begin{aligned} P(X = 1 \; \textrm{and} \; Y = -1) & = \frac{p}{2}, \\ P(X = 1 \; \textrm{and} \; Y = 3) & = \frac{1-p}{2}, \\ P(X = 3 \; \textrm{and} \; Y = -1) & = \frac{1-p}{2}, \\ P(X = 3 \; \textrm{and} \; Y = 3) & = \frac{p}{2}, \end{aligned}\end{split}\]

where \(p\) is a parameter in \([0,1]\) we get to pick. Notice that if \(p=1\) then they are both always their minimum or maximum values simultaneously, and if \(p=0\) they are guaranteed to take their flipped values simultaneously (one is large when the other is small and vice versa). If \(p=1/2\), then the four possibilities are all equally likely, and neither should be related. Let’s compute the covariance. First, note \(\mu_X = 2\) and \(\mu_Y = 1\), so we may compute using (22.6.39):

(22.6.41)\[\begin{split}\begin{aligned} \textrm{Cov}(X, Y) & = \sum_{i, j} (x_i - \mu_X) (y_j-\mu_Y) p_{ij} \\ & = (1-2)(-1-1)\frac{p}{2} + (1-2)(3-1)\frac{1-p}{2} + (3-2)(-1-1)\frac{1-p}{2} + (3-2)(3-1)\frac{p}{2} \\ & = 4p-2. \end{aligned}\end{split}\]

When \(p=1\) (the case where they are both maximally positive or negative at the same time) has a covariance of \(2\). When \(p=0\) (the case where they are flipped) the covariance is \(-2\). Finally, when \(p=1/2\) (the case where they are unrelated), the covariance is \(0\). Thus we see that the covariance measures how these two random variables are related.

A quick note on the covariance is that it only measures these linear relationships. More complex relationships like \(X = Y^2\) where \(Y\) is randomly chosen from \(\{-2, -1, 0, 1, 2\}\) with equal probability can be missed. Indeed a quick computation shows that these random variables have covariance zero, despite one being a deterministic function of the other.

For continuous random variables, much the same story holds. At this point, we are pretty comfortable with doing the transition between discrete and continuous, so we will provide the continuous analogue of (22.6.39) without any derivation.

(22.6.42)\[\sigma_{XY} = \int_{\mathbb{R}^2} (x-\mu_X)(y-\mu_Y)p(x, y) \;dx \;dy.\]

For visualization, let’s take a look at a collection of random variables with tunable covariance.

# Plot a few random variables adjustable covariance
covs = [-0.9, 0.0, 1.2]
d2l.plt.figure(figsize=(12, 3))
for i in range(3):
    X = torch.randn(500)
    Y = covs[i]*X + torch.randn(500)

    d2l.plt.subplot(1, 4, i+1)
    d2l.plt.scatter(X.numpy(), Y.numpy())
    d2l.plt.xlabel('X')
    d2l.plt.ylabel('Y')
    d2l.plt.title(f'cov = {covs[i]}')
d2l.plt.show()
../_images/output_random-variables_886f4c_87_0.svg

Let’s see some properties of covariances:

  • For any random variable \(X\), \(\textrm{Cov}(X, X) = \textrm{Var}(X)\).

  • For any random variables \(X, Y\) and numbers \(a\) and \(b\), \(\textrm{Cov}(aX+b, Y) = \textrm{Cov}(X, aY+b) = a\textrm{Cov}(X, Y)\).

  • If \(X\) and \(Y\) are independent then \(\textrm{Cov}(X, Y) = 0\).

In addition, we can use the covariance to expand a relationship we saw before. Recall that is \(X\) and \(Y\) are two independent random variables then

(22.6.43)\[\textrm{Var}(X+Y) = \textrm{Var}(X) + \textrm{Var}(Y).\]

With knowledge of covariances, we can expand this relationship. Indeed, some algebra can show that in general,

(22.6.44)\[\textrm{Var}(X+Y) = \textrm{Var}(X) + \textrm{Var}(Y) + 2\textrm{Cov}(X, Y).\]

This allows us to generalize the variance summation rule for correlated random variables.

22.6.1.11. Correlation

As we did in the case of means and variances, let’s now consider units. If \(X\) is measured in one unit (say inches), and \(Y\) is measured in another (say dollars), the covariance is measured in the product of these two units \(\textrm{inches} \times \textrm{dollars}\). These units can be hard to interpret. What we will often want in this case is a unit-less measurement of relatedness. Indeed, often we do not care about exact quantitative correlation, but rather ask if the correlation is in the same direction, and how strong the relationship is.

To see what makes sense, let’s perform a thought experiment. Suppose that we convert our random variables in inches and dollars to be in inches and cents. In this case the random variable \(Y\) is multiplied by \(100\). If we work through the definition, this means that \(\textrm{Cov}(X, Y)\) will be multiplied by \(100\). Thus we see that in this case a change of units change the covariance by a factor of \(100\). Thus, to find our unit-invariant measure of correlation, we will need to divide by something else that also gets scaled by \(100\). Indeed we have a clear candidate, the standard deviation! Indeed if we define the correlation coefficient to be

(22.6.45)\[\rho(X, Y) = \frac{\textrm{Cov}(X, Y)}{\sigma_{X}\sigma_{Y}},\]

we see that this is a unit-less value. A little mathematics can show that this number is between \(-1\) and \(1\) with \(1\) meaning maximally positively correlated, whereas \(-1\) means maximally negatively correlated.

Returning to our explicit discrete example above, we can see that \(\sigma_X = 1\) and \(\sigma_Y = 2\), so we can compute the correlation between the two random variables using (22.6.45) to see that

(22.6.46)\[\rho(X, Y) = \frac{4p-2}{1\cdot 2} = 2p-1.\]

This now ranges between \(-1\) and \(1\) with the expected behavior of \(1\) meaning most correlated, and \(-1\) meaning minimally correlated.

As another example, consider \(X\) as any random variable, and \(Y=aX+b\) as any linear deterministic function of \(X\). Then, one can compute that

(22.6.47)\[\sigma_{Y} = \sigma_{aX+b} = |a|\sigma_{X},\]
(22.6.48)\[\textrm{Cov}(X, Y) = \textrm{Cov}(X, aX+b) = a\textrm{Cov}(X, X) = a\textrm{Var}(X),\]

and thus by (22.6.45) that

(22.6.49)\[\rho(X, Y) = \frac{a\textrm{Var}(X)}{|a|\sigma_{X}^2} = \frac{a}{|a|} = \textrm{sign}(a).\]

Thus we see that the correlation is \(+1\) for any \(a > 0\), and \(-1\) for any \(a < 0\) illustrating that correlation measures the degree and directionality the two random variables are related, not the scale that the variation takes.

Let’s again plot a collection of random variables with tunable correlation.

# Plot a few random variables adjustable correlations
cors = [-0.9, 0.0, 1.0]
d2l.plt.figure(figsize=(12, 3))
for i in range(3):
    X = torch.randn(500)
    Y = cors[i] * X + torch.sqrt(torch.tensor(1) -
                                 cors[i]**2) * torch.randn(500)

    d2l.plt.subplot(1, 4, i + 1)
    d2l.plt.scatter(X.numpy(), Y.numpy())
    d2l.plt.xlabel('X')
    d2l.plt.ylabel('Y')
    d2l.plt.title(f'cor = {cors[i]}')
d2l.plt.show()
../_images/output_random-variables_886f4c_99_0.svg

Let’s list a few properties of the correlation below.

  • For any random variable \(X\), \(\rho(X, X) = 1\).

  • For any random variables \(X, Y\) and numbers \(a\) and \(b\), \(\rho(aX+b, Y) = \rho(X, aY+b) = \rho(X, Y)\).

  • If \(X\) and \(Y\) are independent with non-zero variance then \(\rho(X, Y) = 0\).

As a final note, you may feel like some of these formulae are familiar. Indeed, if we expand everything out assuming that \(\mu_X = \mu_Y = 0\), we see that this is

(22.6.50)\[\rho(X, Y) = \frac{\sum_{i, j} x_iy_ip_{ij}}{\sqrt{\sum_{i, j}x_i^2 p_{ij}}\sqrt{\sum_{i, j}y_j^2 p_{ij}}}.\]

This looks like a sum of a product of terms divided by the square root of sums of terms. This is exactly the formula for the cosine of the angle between two vectors \(\mathbf{v}, \mathbf{w}\) with the different coordinates weighted by \(p_{ij}\):

(22.6.51)\[\cos(\theta) = \frac{\mathbf{v}\cdot \mathbf{w}}{\|\mathbf{v}\|\|\mathbf{w}\|} = \frac{\sum_{i} v_iw_i}{\sqrt{\sum_{i}v_i^2}\sqrt{\sum_{i}w_i^2}}.\]

Indeed if we think of norms as being related to standard deviations, and correlations as being cosines of angles, much of the intuition we have from geometry can be applied to thinking about random variables.

22.6.2. Summary

  • Continuous random variables are random variables that can take on a continuum of values. They have some technical difficulties that make them more challenging to work with compared to discrete random variables.

  • The probability density function allows us to work with continuous random variables by giving a function where the area under the curve on some interval gives the probability of finding a sample point in that interval.

  • The cumulative distribution function is the probability of observing the random variable to be less than a given threshold. It can provide a useful alternate viewpoint which unifies discrete and continuous variables.

  • The mean is the average value of a random variable.

  • The variance is the expected square of the difference between the random variable and its mean.

  • The standard deviation is the square root of the variance. It can be thought of as measuring the range of values the random variable may take.

  • Chebyshev’s inequality allows us to make this intuition rigorous by giving an explicit interval that contains the random variable most of the time.

  • Joint densities allow us to work with correlated random variables. We may marginalize joint densities by integrating over unwanted random variables to get the distribution of the desired random variable.

  • The covariance and correlation coefficient provide a way to measure any linear relationship between two correlated random variables.

22.6.3. Exercises

  1. Suppose that we have the random variable with density given by \(p(x) = \frac{1}{x^2}\) for \(x \ge 1\) and \(p(x) = 0\) otherwise. What is \(P(X > 2)\)?

  2. The Laplace distribution is a random variable whose density is given by \(p(x = \frac{1}{2}e^{-|x|}\). What is the mean and the standard deviation of this function? As a hint, \(\int_0^\infty xe^{-x} \; dx = 1\) and \(\int_0^\infty x^2e^{-x} \; dx = 2\).

  3. I walk up to you on the street and say “I have a random variable with mean \(1\), standard deviation \(2\), and I observed \(25\%\) of my samples taking a value larger than \(9\).” Do you believe me? Why or why not?

  4. Suppose that you have two random variables \(X, Y\), with joint density given by \(p_{XY}(x, y) = 4xy\) for \(x, y \in [0,1]\) and \(p_{XY}(x, y) = 0\) otherwise. What is the covariance of \(X\) and \(Y\)?

4.4. Softmax Regression Implementation from Scratch Open the notebook in SageMaker Studio Lab

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

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

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

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

4.4. Softmax Regression Implementation from Scratch
Open the notebook in SageMaker Studio Lab

Because softmax regression is so fundamental, we believe that you ought to know how to implement it yourself. Here, we limit ourselves to defining the softmax-specific aspects of the model and reuse the other components from our linear regression section, including the training loop.

import torch
from d2l import torch as d2l

4.4.1. The Softmax

Let’s begin with the most important part: the mapping from scalars to probabilities. For a refresher, recall the operation of the sum operator along specific dimensions in a tensor, as discussed in Section 2.3.6 and Section 2.3.7. Given a matrix X we can sum over all elements (by default) or only over elements in the same axis. The axis variable lets us compute row and column sums:

X = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
X.sum(0, keepdims=True), X.sum(1, keepdims=True)
(tensor([[5., 7., 9.]]),
 tensor([[ 6.],
         [15.]]))

Computing the softmax requires three steps: (i) exponentiation of each term; (ii) a sum over each row to compute the normalization constant for each example; (iii) division of each row by its normalization constant, ensuring that the result sums to 1:

(4.4.1)\[\mathrm{softmax}(\mathbf{X})_{ij} = \frac{\exp(\mathbf{X}_{ij})}{\sum_k \exp(\mathbf{X}_{ik})}.\]

The (logarithm of the) denominator is called the (log) partition function. It was introduced in statistical physics to sum over all possible states in a thermodynamic ensemble. The implementation is straightforward:

def softmax(X):
    X_exp = torch.exp(X)
    partition = X_exp.sum(1, keepdims=True)
    return X_exp / partition  # The broadcasting mechanism is applied here

For any input X, we turn each element into a nonnegative number. Each row sums up to 1, as is required for a probability. Caution: the code above is not robust against very large or very small arguments. While it is sufficient to illustrate what is happening, you should not use this code verbatim for any serious purpose. Deep learning frameworks have such protections built in and we will be using the built-in softmax going forward.

X = torch.rand((2, 5))
X_prob = softmax(X)
X_prob, X_prob.sum(1)
(tensor([[0.2511, 0.1417, 0.1158, 0.2529, 0.2385],
         [0.2004, 0.1419, 0.1957, 0.2504, 0.2117]]),
 tensor([1., 1.]))

4.4.2. The Model

We now have everything that we need to implement the softmax regression model. As in our linear regression example, each instance will be represented by a fixed-length vector. Since the raw data here consists of \(28 \times 28\) pixel images, we flatten each image, treating them as vectors of length 784. In later chapters, we will introduce convolutional neural networks, which exploit the spatial structure in a more satisfying way.

In softmax regression, the number of outputs from our network should be equal to the number of classes. Since our dataset has 10 classes, our network has an output dimension of 10. Consequently, our weights constitute a \(784 \times 10\) matrix plus a \(1 \times 10\) row vector for the biases. As with linear regression, we initialize the weights W with Gaussian noise. The biases are initialized as zeros.

class SoftmaxRegressionScratch(d2l.Classifier):
    def __init__(self, num_inputs, num_outputs, lr, sigma=0.01):
        super().__init__()
        self.save_hyperparameters()
        self.W = torch.normal(0, sigma, size=(num_inputs, num_outputs),
                              requires_grad=True)
        self.b = torch.zeros(num_outputs, requires_grad=True)

    def parameters(self):
        return [self.W, self.b]

The code below defines how the network maps each input to an output. Note that we flatten each \(28 \times 28\) pixel image in the batch into a vector using reshape before passing the data through our model.

@d2l.add_to_class(SoftmaxRegressionScratch)
def forward(self, X):
    X = X.reshape((-1, self.W.shape[0]))
    return softmax(torch.matmul(X, self.W) + self.b)

4.4.3. The Cross-Entropy Loss

Next we need to implement the cross-entropy loss function (introduced in Section 4.1.2). This may be the most common loss function in all of deep learning. At the moment, applications of deep learning easily cast as classification problems far outnumber those better treated as regression problems.

Recall that cross-entropy takes the negative log-likelihood of the predicted probability assigned to the true label. For efficiency we avoid Python for-loops and use indexing instead. In particular, the one-hot encoding in \(\mathbf{y}\) allows us to select the matching terms in \(\hat{\mathbf{y}}\).

To see this in action we create sample data y_hat with 2 examples of predicted probabilities over 3 classes and their corresponding labels y. The correct labels are \(0\) and \(2\) respectively (i.e., the first and third class). Using y as the indices of the probabilities in y_hat, we can pick out terms efficiently.

y = torch.tensor([0, 2])
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y_hat[[0, 1], y]
tensor([0.1000, 0.5000])

Now we can implement the cross-entropy loss function by averaging over the logarithms of the selected probabilities.

def cross_entropy(y_hat, y):
    return -torch.log(y_hat[list(range(len(y_hat))), y]).mean()

cross_entropy(y_hat, y)
tensor(1.4979)
@d2l.add_to_class(SoftmaxRegressionScratch)
def loss(self, y_hat, y):
    return cross_entropy(y_hat, y)

4.4.4. Training

We reuse the fit method defined in Section 3.4 to train the model with 10 epochs. Note that the number of epochs (max_epochs), the minibatch size (batch_size), and learning rate (lr) are adjustable hyperparameters. That means that while these values are not learned during our primary training loop, they still influence the performance of our model, both vis-à-vis training and generalization performance. In practice you will want to choose these values based on the validation split of the data and then, ultimately, to evaluate your final model on the test split. As discussed in Section 3.6.3, we will regard the test data of Fashion-MNIST as the validation set, thus reporting validation loss and validation accuracy on this split.

data = d2l.FashionMNIST(batch_size=256)
model = SoftmaxRegressionScratch(num_inputs=784, num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)
../_images/output_softmax-regression-scratch_aecde8_120_0.svg

4.4.5. Prediction

Now that training is complete, our model is ready to classify some images.

X, y = next(iter(data.val_dataloader()))
preds = model(X).argmax(axis=1)
preds.shape
torch.Size([256])

We are more interested in the images we label incorrectly. We visualize them by comparing their actual labels (first line of text output) with the predictions from the model (second line of text output).

wrong = preds.type(y.dtype) != y
X, y, preds = X[wrong], y[wrong], preds[wrong]
labels = [a+'\n'+b for a, b in zip(
    data.text_labels(y), data.text_labels(preds))]
data.visualize([X, y], labels=labels)
../_images/output_softmax-regression-scratch_aecde8_150_0.svg

4.4.6. Summary

By now we are starting to get some experience with solving linear regression and classification problems. With it, we have reached what would arguably be the state of the art of 1960–1970s of statistical modeling. In the next section, we will show you how to leverage deep learning frameworks to implement this model much more efficiently.

4.4.7. Exercises

  1. In this section, we directly implemented the softmax function based on the mathematical definition of the softmax operation. As discussed in Section 4.1 this can cause numerical instabilities.

    1. Test whether softmax still works correctly if an input has a value of \(100\).

    2. Test whether softmax still works correctly if the largest of all inputs is smaller than \(-100\)?

    3. Implement a fix by looking at the value relative to the largest entry in the argument.

  2. Implement a cross_entropy function that follows the definition of the cross-entropy loss function \(\sum_i y_i \log \hat{y}_i\).

    1. Try it out in the code example of this section.

    2. Why do you think it runs more slowly?

    3. Should you use it? When would it make sense to?

    4. What do you need to be careful of? Hint: consider the domain of the logarithm.

  3. Is it always a good idea to return the most likely label? For example, would you do this for medical diagnosis? How would you try to address this?

  4. Assume that we want to use softmax regression to predict the next word based on some features. What are some problems that might arise from a large vocabulary?

  5. Experiment with the hyperparameters of the code in this section. In particular:

    1. Plot how the validation loss changes as you change the learning rate.

    2. Do the validation and training loss change as you change the minibatch size? How large or small do you need to go before you see an effect?

11.6. Self-Attention and Positional Encoding Open the notebook in SageMaker Studio Lab

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

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

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

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

11.6. Self-Attention and Positional Encoding
Open the notebook in SageMaker Studio Lab

In deep learning, we often use CNNs or RNNs to encode sequences. Now with attention mechanisms in mind, imagine feeding a sequence of tokens into an attention mechanism such that at every step, each token has its own query, keys, and values. Here, when computing the value of a token’s representation at the next layer, the token can attend (via its query vector) to any other’s token (matching based on their key vectors). Using the full set of query-key compatibility scores, we can compute, for each token, a representation by building the appropriate weighted sum over the other tokens. Because every token is attending to each other token (unlike the case where decoder steps attend to encoder steps), such architectures are typically described as self-attention models (Lin et al., 2017, Vaswani et al., 2017), and elsewhere described as intra-attention model (Cheng et al., 2016, Parikh et al., 2016, Paulus et al., 2017). In this section, we will discuss sequence encoding using self-attention, including using additional information for the sequence order.

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

11.6.1. Self-Attention

Given a sequence of input tokens \(\mathbf{x}_1, \ldots, \mathbf{x}_n\) where any \(\mathbf{x}_i \in \mathbb{R}^d\) (\(1 \leq i \leq n\)), its self-attention outputs a sequence of the same length \(\mathbf{y}_1, \ldots, \mathbf{y}_n\), where

(11.6.1)\[\mathbf{y}_i = f(\mathbf{x}_i, (\mathbf{x}_1, \mathbf{x}_1), \ldots, (\mathbf{x}_n, \mathbf{x}_n)) \in \mathbb{R}^d\]

according to the definition of attention pooling in (11.1.1). Using multi-head attention, the following code snippet computes the self-attention of a tensor with shape (batch size, number of time steps or sequence length in tokens, \(d\)). The output tensor has the same shape.

num_hiddens, num_heads = 100, 5
attention = d2l.MultiHeadAttention(num_hiddens, num_heads, 0.5)
batch_size, num_queries, valid_lens = 2, 4, torch.tensor([3, 2])
X = torch.ones((batch_size, num_queries, num_hiddens))
d2l.check_shape(attention(X, X, X, valid_lens),
                (batch_size, num_queries, num_hiddens))

11.6.2. Comparing CNNs, RNNs, and Self-Attention

Let’s compare architectures for mapping a sequence of \(n\) tokens to another one of equal length, where each input or output token is represented by a \(d\)-dimensional vector. Specifically, we will consider CNNs, RNNs, and self-attention. We will compare their computational complexity, sequential operations, and maximum path lengths. Note that sequential operations prevent parallel computation, while a shorter path between any combination of sequence positions makes it easier to learn long-range dependencies within the sequence (Hochreiter et al., 2001).

../_images/cnn-rnn-self-attention.svg

Fig. 11.6.1 Comparing CNN (padding tokens are omitted), RNN, and self-attention architectures.

Let’s regard any text sequence as a “one-dimensional image”. Similarly, one-dimensional CNNs can process local features such as \(n\)-grams in text. Given a sequence of length \(n\), consider a convolutional layer whose kernel size is \(k\), and whose numbers of input and output channels are both \(d\). The computational complexity of the convolutional layer is \(\mathcal{O}(knd^2)\). As Fig. 11.6.1 shows, CNNs are hierarchical, so there are \(\mathcal{O}(1)\) sequential operations and the maximum path length is \(\mathcal{O}(n/k)\). For example, \(\mathbf{x}_1\) and \(\mathbf{x}_5\) are within the receptive field of a two-layer CNN with kernel size 3 in Fig. 11.6.1.

When updating the hidden state of RNNs, multiplication of the \(d \times d\) weight matrix and the \(d\)-dimensional hidden state has a computational complexity of \(\mathcal{O}(d^2)\). Since the sequence length is \(n\), the computational complexity of the recurrent layer is \(\mathcal{O}(nd^2)\). According to Fig. 11.6.1, there are \(\mathcal{O}(n)\) sequential operations that cannot be parallelized and the maximum path length is also \(\mathcal{O}(n)\).

In self-attention, the queries, keys, and values are all \(n \times d\) matrices. Consider the scaled dot product attention in (11.3.6), where an \(n \times d\) matrix is multiplied by a \(d \times n\) matrix, then the output \(n \times n\) matrix is multiplied by an \(n \times d\) matrix. As a result, the self-attention has a \(\mathcal{O}(n^2d)\) computational complexity. As we can see from Fig. 11.6.1, each token is directly connected to any other token via self-attention. Therefore, computation can be parallel with \(\mathcal{O}(1)\) sequential operations and the maximum path length is also \(\mathcal{O}(1)\).

All in all, both CNNs and self-attention enjoy parallel computation and self-attention has the shortest maximum path length. However, the quadratic computational complexity with respect to the sequence length makes self-attention prohibitively slow for very long sequences.

11.6.3. Positional Encoding

Unlike RNNs, which recurrently process tokens of a sequence one-by-one, self-attention ditches sequential operations in favor of parallel computation. Note that self-attention by itself does not preserve the order of the sequence. What do we do if it really matters that the model knows in which order the input sequence arrived?

The dominant approach for preserving information about the order of tokens is to represent this to the model as an additional input associated with each token. These inputs are called positional encodings, and they can either be learned or fixed a priori. We now describe a simple scheme for fixed positional encodings based on sine and cosine functions (Vaswani et al., 2017).

Suppose that the input representation \(\mathbf{X} \in \mathbb{R}^{n \times d}\) contains the \(d\)-dimensional embeddings for \(n\) tokens of a sequence. The positional encoding outputs \(\mathbf{X} + \mathbf{P}\) using a positional embedding matrix \(\mathbf{P} \in \mathbb{R}^{n \times d}\) of the same shape, whose element on the \(i^\textrm{th}\) row and the \((2j)^\textrm{th}\) or the \((2j + 1)^\textrm{th}\) column is

(11.6.2)\[\begin{split}\begin{aligned} p_{i, 2j} &= \sin\left(\frac{i}{10000^{2j/d}}\right),\\p_{i, 2j+1} &= \cos\left(\frac{i}{10000^{2j/d}}\right).\end{aligned}\end{split}\]

At first glance, this trigonometric function design looks weird. Before we give explanations of this design, let’s first implement it in the following PositionalEncoding class.

class PositionalEncoding(nn.Module):  #@save
    """Positional encoding."""
    def __init__(self, num_hiddens, dropout, max_len=1000):
        super().__init__()
        self.dropout = nn.Dropout(dropout)
        # Create a long enough P
        self.P = torch.zeros((1, max_len, num_hiddens))
        X = torch.arange(max_len, dtype=torch.float32).reshape(
            -1, 1) / torch.pow(10000, torch.arange(
            0, num_hiddens, 2, dtype=torch.float32) / num_hiddens)
        self.P[:, :, 0::2] = torch.sin(X)
        self.P[:, :, 1::2] = torch.cos(X)

    def forward(self, X):
        X = X + self.P[:, :X.shape[1], :].to(X.device)
        return self.dropout(X)

In the positional embedding matrix \(\mathbf{P}\), rows correspond to positions within a sequence and columns represent different positional encoding dimensions. In the example below, we can see that the \(6^{\textrm{th}}\) and the \(7^{\textrm{th}}\) columns of the positional embedding matrix have a higher frequency than the \(8^{\textrm{th}}\) and the \(9^{\textrm{th}}\) columns. The offset between the \(6^{\textrm{th}}\) and the \(7^{\textrm{th}}\) (same for the \(8^{\textrm{th}}\) and the \(9^{\textrm{th}}\)) columns is due to the alternation of sine and cosine functions.

encoding_dim, num_steps = 32, 60
pos_encoding = PositionalEncoding(encoding_dim, 0)
X = pos_encoding(torch.zeros((1, num_steps, encoding_dim)))
P = pos_encoding.P[:, :X.shape[1], :]
d2l.plot(torch.arange(num_steps), P[0, :, 6:10].T, xlabel='Row (position)',
         figsize=(6, 2.5), legend=["Col %d" % d for d in torch.arange(6, 10)])
../_images/output_self-attention-and-positional-encoding_ce9eb6_48_0.svg

11.6.3.1. Absolute Positional Information

To see how the monotonically decreased frequency along the encoding dimension relates to absolute positional information, let’s print out the binary representations of \(0, 1, \ldots, 7\). As we can see, the lowest bit, the second-lowest bit, and the third-lowest bit alternate on every number, every two numbers, and every four numbers, respectively.

for i in range(8):
    print(f'{i} in binary is {i:>03b}')
0 in binary is 000
1 in binary is 001
2 in binary is 010
3 in binary is 011
4 in binary is 100
5 in binary is 101
6 in binary is 110
7 in binary is 111

In binary representations, a higher bit has a lower frequency than a lower bit. Similarly, as demonstrated in the heat map below, the positional encoding decreases frequencies along the encoding dimension by using trigonometric functions. Since the outputs are float numbers, such continuous representations are more space-efficient than binary representations.

P = P[0, :, :].unsqueeze(0).unsqueeze(0)
d2l.show_heatmaps(P, xlabel='Column (encoding dimension)',
                  ylabel='Row (position)', figsize=(3.5, 4), cmap='Blues')
../_images/output_self-attention-and-positional-encoding_ce9eb6_78_0.svg

11.6.3.2. Relative Positional Information

Besides capturing absolute positional information, the above positional encoding also allows a model to easily learn to attend by relative positions. This is because for any fixed position offset \(\delta\), the positional encoding at position \(i + \delta\) can be represented by a linear projection of that at position \(i\).

This projection can be explained mathematically. Denoting \(\omega_j = 1/10000^{2j/d}\), any pair of \((p_{i, 2j}, p_{i, 2j+1})\) in (11.6.2) can be linearly projected to \((p_{i+\delta, 2j}, p_{i+\delta, 2j+1})\) for any fixed offset \(\delta\):

(11.6.3)\[\begin{split}\begin{aligned} \begin{bmatrix} \cos(\delta \omega_j) & \sin(\delta \omega_j) \\ -\sin(\delta \omega_j) & \cos(\delta \omega_j) \\ \end{bmatrix} \begin{bmatrix} p_{i, 2j} \\ p_{i, 2j+1} \\ \end{bmatrix} =&\begin{bmatrix} \cos(\delta \omega_j) \sin(i \omega_j) + \sin(\delta \omega_j) \cos(i \omega_j) \\ -\sin(\delta \omega_j) \sin(i \omega_j) + \cos(\delta \omega_j) \cos(i \omega_j) \\ \end{bmatrix}\\ =&\begin{bmatrix} \sin\left((i+\delta) \omega_j\right) \\ \cos\left((i+\delta) \omega_j\right) \\ \end{bmatrix}\\ =& \begin{bmatrix} p_{i+\delta, 2j} \\ p_{i+\delta, 2j+1} \\ \end{bmatrix}, \end{aligned}\end{split}\]

where the \(2\times 2\) projection matrix does not depend on any position index \(i\).

11.6.4. Summary

In self-attention, the queries, keys, and values all come from the same place. Both CNNs and self-attention enjoy parallel computation and self-attention has the shortest maximum path length. However, the quadratic computational complexity with respect to the sequence length makes self-attention prohibitively slow for very long sequences. To use the sequence order information, we can inject absolute or relative positional information by adding positional encoding to the input representations.

11.6.5. Exercises

  1. Suppose that we design a deep architecture to represent a sequence by stacking self-attention layers with positional encoding. What could the possible issues be?

  2. Can you design a learnable positional encoding method?

  3. Can we assign different learned embeddings according to different offsets between queries and keys that are compared in self-attention? Hint: you may refer to relative position embeddings (Huang et al., 2018, Shaw et al., 2018).

8.2. Feature extraction

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.2. Feature extraction

The sklearn.feature_extraction module can be used to extract features in a format supported by machine learning algorithms from datasets consisting of formats such as text and image.

Note

Feature extraction is very different from Feature selection: the former consists of transforming arbitrary data, such as text or images, into numerical features usable for machine learning. The latter is a machine learning technique applied to these features.

8.2.1. Loading features from dicts

The class DictVectorizer can be used to convert feature arrays represented as lists of standard Python dict objects to the NumPy/SciPy representation used by scikit-learn estimators.

While not particularly fast to process, Python’s dict has the advantages of being convenient to use, being sparse (absent features need not be stored) and storing feature names in addition to values.

DictVectorizer implements what is called one-of-K or “one-hot” coding for categorical (aka nominal, discrete) features. Categorical features are “attribute-value” pairs where the value is restricted to a list of discrete possibilities without ordering (e.g. topic identifiers, types of objects, tags, names…).

In the following, “city” is a categorical attribute while “temperature” is a traditional numerical feature:

>>> measurements = [
...     {'city': 'Dubai', 'temperature': 33.},
...     {'city': 'London', 'temperature': 12.},
...     {'city': 'San Francisco', 'temperature': 18.},
... ]

>>> from sklearn.feature_extraction import DictVectorizer
>>> vec = DictVectorizer()

>>> vec.fit_transform(measurements).toarray()
array([[ 1.,  0.,  0., 33.],
       [ 0.,  1.,  0., 12.],
       [ 0.,  0.,  1., 18.]])

>>> vec.get_feature_names_out()
array(['city=Dubai', 'city=London', 'city=San Francisco', 'temperature'], ...)

DictVectorizer accepts multiple string values for one feature, like, e.g., multiple categories for a movie.

Assume a database classifies each movie using some categories (not mandatory) and its year of release.

>>> movie_entry = [{'category': ['thriller', 'drama'], 'year': 2003},
...                {'category': ['animation', 'family'], 'year': 2011},
...                {'year': 1974}]
>>> vec.fit_transform(movie_entry).toarray()
array([[0.000e+00, 1.000e+00, 0.000e+00, 1.000e+00, 2.003e+03],
       [1.000e+00, 0.000e+00, 1.000e+00, 0.000e+00, 2.011e+03],
       [0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 1.974e+03]])
>>> vec.get_feature_names_out()
array(['category=animation', 'category=drama', 'category=family',
       'category=thriller', 'year'], ...)
>>> vec.transform({'category': ['thriller'],
...                'unseen_feature': '3'}).toarray()
array([[0., 0., 0., 1., 0.]])

DictVectorizer is also a useful representation transformation for training sequence classifiers in Natural Language Processing models that typically work by extracting feature windows around a particular word of interest.

For example, suppose that we have a first algorithm that extracts Part of Speech (PoS) tags that we want to use as complementary tags for training a sequence classifier (e.g. a chunker). The following dict could be such a window of features extracted around the word ‘sat’ in the sentence ‘The cat sat on the mat.’:

>>> pos_window = [
...     {
...         'word-2': 'the',
...         'pos-2': 'DT',
...         'word-1': 'cat',
...         'pos-1': 'NN',
...         'word+1': 'on',
...         'pos+1': 'PP',
...     },
...     # in a real application one would extract many such dictionaries
... ]

This description can be vectorized into a sparse two-dimensional matrix suitable for feeding into a classifier (maybe after being piped into a TfidfTransformer for normalization):

>>> vec = DictVectorizer()
>>> pos_vectorized = vec.fit_transform(pos_window)
>>> pos_vectorized
<Compressed Sparse...dtype 'float64'
  with 6 stored elements and shape (1, 6)>
>>> pos_vectorized.toarray()
array([[1., 1., 1., 1., 1., 1.]])
>>> vec.get_feature_names_out()
array(['pos+1=PP', 'pos-1=NN', 'pos-2=DT', 'word+1=on', 'word-1=cat',
       'word-2=the'], ...)

As you can imagine, if one extracts such a context around each individual word of a corpus of documents the resulting matrix will be very wide (many one-hot-features) with most of them being valued to zero most of the time. So as to make the resulting data structure able to fit in memory the DictVectorizer class uses a scipy.sparse matrix by default instead of a numpy.ndarray.

8.2.2. Feature hashing

The class FeatureHasher is a high-speed, low-memory vectorizer that uses a technique known as feature hashing, or the “hashing trick”. Instead of building a hash table of the features encountered in training, as the vectorizers do, instances of FeatureHasher apply a hash function to the features to determine their column index in sample matrices directly. The result is increased speed and reduced memory usage, at the expense of inspectability; the hasher does not remember what the input features looked like and has no inverse_transform method.

Since the hash function might cause collisions between (unrelated) features, a signed hash function is used and the sign of the hash value determines the sign of the value stored in the output matrix for a feature. This way, collisions are likely to cancel out rather than accumulate error, and the expected mean of any output feature’s value is zero. This mechanism is enabled by default with alternate_sign=True and is particularly useful for small hash table sizes (n_features < 10000). For large hash table sizes, it can be disabled, to allow the output to be passed to estimators like MultinomialNB or chi2 feature selectors that expect non-negative inputs.

FeatureHasher accepts either mappings (like Python’s dict and its variants in the collections module), (feature, value) pairs, or strings, depending on the constructor parameter input_type. Mappings are treated as lists of (feature, value) pairs, while single strings have an implicit value of 1, so ['feat1', 'feat2', 'feat3'] is interpreted as [('feat1', 1), ('feat2', 1), ('feat3', 1)]. If a single feature occurs multiple times in a sample, the associated values will be summed (so ('feat', 2) and ('feat', 3.5) become ('feat', 5.5)). The output from FeatureHasher is always a scipy.sparse matrix in the CSR format.

Feature hashing can be employed in document classification, but unlike CountVectorizer, FeatureHasher does not do word splitting or any other preprocessing except Unicode-to-UTF-8 encoding; see Vectorizing a large text corpus with the hashing trick, below, for a combined tokenizer/hasher.

As an example, consider a word-level natural language processing task that needs features extracted from (token, part_of_speech) pairs. One could use a Python generator function to extract features:

def token_features(token, part_of_speech):
    if token.isdigit():
        yield "numeric"
    else:
        yield "token={}".format(token.lower())
        yield "token,pos={},{}".format(token, part_of_speech)
    if token[0].isupper():
        yield "uppercase_initial"
    if token.isupper():
        yield "all_uppercase"
    yield "pos={}".format(part_of_speech)

Then, the raw_X to be fed to FeatureHasher.transform can be constructed using:

raw_X = (token_features(tok, pos_tagger(tok)) for tok in corpus)

and fed to a hasher with:

hasher = FeatureHasher(input_type='string')
X = hasher.transform(raw_X)

to get a scipy.sparse matrix X.

Note the use of a generator comprehension, which introduces laziness into the feature extraction: tokens are only processed on demand from the hasher.

Implementation details

FeatureHasher uses the signed 32-bit variant of MurmurHash3. As a result (and because of limitations in scipy.sparse), the maximum number of features supported is currently \(2^{31} - 1\).

The original formulation of the hashing trick by Weinberger et al. used two separate hash functions \(h\) and \(\xi\) to determine the column index and sign of a feature, respectively. The present implementation works under the assumption that the sign bit of MurmurHash3 is independent of its other bits.

Since a simple modulo is used to transform the hash function to a column index, it is advisable to use a power of two as the n_features parameter; otherwise the features will not be mapped evenly to the columns.

References

References

8.2.3. Text feature extraction

8.2.3.1. The Bag of Words representation

Text Analysis is a major application field for machine learning algorithms. However the raw data, a sequence of symbols, cannot be fed directly to the algorithms themselves as most of them expect numerical feature vectors with a fixed size rather than the raw text documents with variable length.

In order to address this, scikit-learn provides utilities for the most common ways to extract numerical features from text content, namely:

  • tokenizing strings and giving an integer id for each possible token, for instance by using white-spaces and punctuation as token separators.

  • counting the occurrences of tokens in each document.

  • normalizing and weighting with diminishing importance tokens that occur in the majority of samples / documents.

In this scheme, features and samples are defined as follows:

  • each individual token occurrence frequency (normalized or not) is treated as a feature.

  • the vector of all the token frequencies for a given document is considered a multivariate sample.

A corpus of documents can thus be represented by a matrix with one row per document and one column per token (e.g. word) occurring in the corpus.

We call vectorization the general process of turning a collection of text documents into numerical feature vectors. This specific strategy (tokenization, counting and normalization) is called the Bag of Words or “Bag of n-grams” representation. Documents are described by word occurrences while completely ignoring the relative position information of the words in the document.

8.2.3.2. Sparsity

As most documents will typically use a very small subset of the words used in the corpus, the resulting matrix will have many feature values that are zeros (typically more than 99% of them).

For instance a collection of 10,000 short text documents (such as emails) will use a vocabulary with a size in the order of 100,000 unique words in total while each document will use 100 to 1000 unique words individually.

In order to be able to store such a matrix in memory but also to speed up algebraic operations matrix / vector, implementations will typically use a sparse representation such as the implementations available in the scipy.sparse package.

8.2.3.3. Common Vectorizer usage

CountVectorizer implements both tokenization and occurrence counting in a single class:

>>> from sklearn.feature_extraction.text import CountVectorizer

This model has many parameters, however the default values are quite reasonable (please see the reference documentation for the details):

>>> vectorizer = CountVectorizer()
>>> vectorizer
CountVectorizer()

Let’s use it to tokenize and count the word occurrences of a minimalistic corpus of text documents:

>>> corpus = [
...     'This is the first document.',
...     'This is the second second document.',
...     'And the third one.',
...     'Is this the first document?',
... ]
>>> X = vectorizer.fit_transform(corpus)
>>> X
<Compressed Sparse...dtype 'int64'
  with 19 stored elements and shape (4, 9)>

The default configuration tokenizes the string by extracting words of at least 2 letters. The specific function that does this step can be requested explicitly:

>>> analyze = vectorizer.build_analyzer()
>>> analyze("This is a text document to analyze.") == (
...     ['this', 'is', 'text', 'document', 'to', 'analyze'])
True

Each term found by the analyzer during the fit is assigned a unique integer index corresponding to a column in the resulting matrix. This interpretation of the columns can be retrieved as follows:

>>> vectorizer.get_feature_names_out()
array(['and', 'document', 'first', 'is', 'one', 'second', 'the',
       'third', 'this'], ...)

>>> X.toarray()
array([[0, 1, 1, 1, 0, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 2, 1, 0, 1],
       [1, 0, 0, 0, 1, 0, 1, 1, 0],
       [0, 1, 1, 1, 0, 0, 1, 0, 1]]...)

The converse mapping from feature name to column index is stored in the vocabulary_ attribute of the vectorizer:

>>> vectorizer.vocabulary_.get('document')
1

Hence words that were not seen in the training corpus will be completely ignored in future calls to the transform method:

>>> vectorizer.transform(['Something completely new.']).toarray()
array([[0, 0, 0, 0, 0, 0, 0, 0, 0]]...)

Note that in the previous corpus, the first and the last documents have exactly the same words hence are encoded in equal vectors. In particular we lose the information that the last document is an interrogative form. To preserve some of the local ordering information we can extract 2-grams of words in addition to the 1-grams (individual words):

>>> bigram_vectorizer = CountVectorizer(ngram_range=(1, 2),
...                                     token_pattern=r'\b\w+\b', min_df=1)
>>> analyze = bigram_vectorizer.build_analyzer()
>>> analyze('Bi-grams are cool!') == (
...     ['bi', 'grams', 'are', 'cool', 'bi grams', 'grams are', 'are cool'])
True

The vocabulary extracted by this vectorizer is hence much bigger and can now resolve ambiguities encoded in local positioning patterns:

>>> X_2 = bigram_vectorizer.fit_transform(corpus).toarray()
>>> X_2
array([[0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0],
       [0, 0, 1, 0, 0, 1, 1, 0, 0, 2, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0],
       [1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0],
       [0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1]]...)

In particular the interrogative form “Is this” is only present in the last document:

>>> feature_index = bigram_vectorizer.vocabulary_.get('is this')
>>> X_2[:, feature_index]
array([0, 0, 0, 1]...)

8.2.3.4. Using stop words

Stop words are words like “and”, “the”, “him”, which are presumed to be uninformative in representing the content of a text, and which may be removed to avoid them being construed as informative for prediction. Sometimes, however, similar words are useful for prediction, such as in classifying writing style or personality.

There are several known issues in our provided ‘english’ stop word list. It does not aim to be a general, ‘one-size-fits-all’ solution as some tasks may require a more custom solution. See [NQY18] for more details.

Please take care in choosing a stop word list. Popular stop word lists may include words that are highly informative to some tasks, such as computer.

You should also make sure that the stop word list has had the same preprocessing and tokenization applied as the one used in the vectorizer. The word we’ve is split into we and ve by CountVectorizer’s default tokenizer, so if we’ve is in stop_words, but ve is not, ve will be retained from we’ve in transformed text. Our vectorizers will try to identify and warn about some kinds of inconsistencies.

References

[NQY18]

J. Nothman, H. Qin and R. Yurchak (2018). “Stop Word Lists in Free Open-source Software Packages”. In Proc. Workshop for NLP Open Source Software.

8.2.3.5. Tf–idf term weighting

In a large text corpus, some words will be very present (e.g. “the”, “a”, “is” in English) hence carrying very little meaningful information about the actual contents of the document. If we were to feed the direct count data directly to a classifier those very frequent terms would shadow the frequencies of rarer yet more interesting terms.

In order to re-weight the count features into floating point values suitable for usage by a classifier it is very common to use the tf–idf transform.

Tf means term-frequency while tf–idf means term-frequency times inverse document-frequency: \(\text{tf-idf(t,d)}=\text{tf(t,d)} \times \text{idf(t)}\).

Using the TfidfTransformer’s default settings, TfidfTransformer(norm='l2', use_idf=True, smooth_idf=True, sublinear_tf=False) the term frequency, the number of times a term occurs in a given document, is multiplied with idf component, which is computed as

\(\text{idf}(t) = \log{\frac{1 + n}{1+\text{df}(t)}} + 1\),

where \(n\) is the total number of documents in the document set, and \(\text{df}(t)\) is the number of documents in the document set that contain term \(t\). The resulting tf-idf vectors are then normalized by the Euclidean norm:

\(v_{norm} = \frac{v}{||v||_2} = \frac{v}{\sqrt{v{_1}^2 + v{_2}^2 + \dots + v{_n}^2}}\).

This was originally a term weighting scheme developed for information retrieval (as a ranking function for search engines results) that has also found good use in document classification and clustering.

The following sections contain further explanations and examples that illustrate how the tf-idfs are computed exactly and how the tf-idfs computed in scikit-learn’s TfidfTransformer and TfidfVectorizer differ slightly from the standard textbook notation that defines the idf as

\(\text{idf}(t) = \log{\frac{n}{1+\text{df}(t)}}.\)

In the TfidfTransformer and TfidfVectorizer with smooth_idf=False, the “1” count is added to the idf instead of the idf’s denominator:

\(\text{idf}(t) = \log{\frac{n}{\text{df}(t)}} + 1\)

This normalization is implemented by the TfidfTransformer class:

>>> from sklearn.feature_extraction.text import TfidfTransformer
>>> transformer = TfidfTransformer(smooth_idf=False)
>>> transformer
TfidfTransformer(smooth_idf=False)

Again please see the reference documentation for the details on all the parameters.

Numeric example of a tf-idf matrix

Let’s take an example with the following counts. The first term is present 100% of the time hence not very interesting. The two other features only in less than 50% of the time hence probably more representative of the content of the documents:

>>> counts = [[3, 0, 1],
...           [2, 0, 0],
...           [3, 0, 0],
...           [4, 0, 0],
...           [3, 2, 0],
...           [3, 0, 2]]
...
>>> tfidf = transformer.fit_transform(counts)
>>> tfidf
<Compressed Sparse...dtype 'float64'
  with 9 stored elements and shape (6, 3)>

>>> tfidf.toarray()
array([[0.81940995, 0.        , 0.57320793],
      [1.        , 0.        , 0.        ],
      [1.        , 0.        , 0.        ],
      [1.        , 0.        , 0.        ],
      [0.47330339, 0.88089948, 0.        ],
      [0.58149261, 0.        , 0.81355169]])

Each row is normalized to have unit Euclidean norm:

\(v_{norm} = \frac{v}{||v||_2} = \frac{v}{\sqrt{v{_1}^2 + v{_2}^2 + \dots + v{_n}^2}}\)

For example, we can compute the tf-idf of the first term in the first document in the counts array as follows:

\(n = 6\)

\(\text{df}(t)_{\text{term1}} = 6\)

\(\text{idf}(t)_{\text{term1}} = \log \frac{n}{\text{df}(t)} + 1 = \log(1)+1 = 1\)

\(\text{tf-idf}_{\text{term1}} = \text{tf} \times \text{idf} = 3 \times 1 = 3\)

Now, if we repeat this computation for the remaining 2 terms in the document, we get

\(\text{tf-idf}_{\text{term2}} = 0 \times (\log(6/1)+1) = 0\)

\(\text{tf-idf}_{\text{term3}} = 1 \times (\log(6/2)+1) \approx 2.0986\)

and the vector of raw tf-idfs:

\(\text{tf-idf}_{\text{raw}} = [3, 0, 2.0986].\)

Then, applying the Euclidean (L2) norm, we obtain the following tf-idfs for document 1:

\(\frac{[3, 0, 2.0986]}{\sqrt{\big(3^2 + 0^2 + 2.0986^2\big)}} = [ 0.819, 0, 0.573].\)

Furthermore, the default parameter smooth_idf=True adds “1” to the numerator and denominator as if an extra document was seen containing every term in the collection exactly once, which prevents zero divisions:

\(\text{idf}(t) = \log{\frac{1 + n}{1+\text{df}(t)}} + 1\)

Using this modification, the tf-idf of the third term in document 1 changes to 1.8473:

\(\text{tf-idf}_{\text{term3}} = 1 \times \log(7/3)+1 \approx 1.8473\)

And the L2-normalized tf-idf changes to

\(\frac{[3, 0, 1.8473]}{\sqrt{\big(3^2 + 0^2 + 1.8473^2\big)}} = [0.8515, 0, 0.5243]\):

>>> transformer = TfidfTransformer()
>>> transformer.fit_transform(counts).toarray()
array([[0.85151335, 0.        , 0.52433293],
      [1.        , 0.        , 0.        ],
      [1.        , 0.        , 0.        ],
      [1.        , 0.        , 0.        ],
      [0.55422893, 0.83236428, 0.        ],
      [0.63035731, 0.        , 0.77630514]])

The weights of each feature computed by the fit method call are stored in a model attribute:

>>> transformer.idf_
array([1., 2.25, 1.84])

As tf-idf is very often used for text features, there is also another class called TfidfVectorizer that combines all the options of CountVectorizer and TfidfTransformer in a single model:

>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> vectorizer = TfidfVectorizer()
>>> vectorizer.fit_transform(corpus)
<Compressed Sparse...dtype 'float64'
  with 19 stored elements and shape (4, 9)>

While the tf-idf normalization is often very useful, there might be cases where the binary occurrence markers might offer better features. This can be achieved by using the binary parameter of CountVectorizer. In particular, some estimators such as Bernoulli Naive Bayes explicitly model discrete boolean random variables. Also, very short texts are likely to have noisy tf-idf values while the binary occurrence info is more stable.

As usual the best way to adjust the feature extraction parameters is to use a cross-validated grid search, for instance by pipelining the feature extractor with a classifier:

Examples

8.2.3.6. Decoding text files

Text is made of characters, but files are made of bytes. These bytes represent characters according to some encoding. To work with text files in Python, their bytes must be decoded to a character set called Unicode. Common encodings are ASCII, Latin-1 (Western Europe), KOI8-R (Russian) and the universal encodings UTF-8 and UTF-16. Many others exist.

Note

An encoding can also be called a ‘character set’, but this term is less accurate: several encodings can exist for a single character set.

The text feature extractors in scikit-learn know how to decode text files, but only if you tell them what encoding the files are in. The CountVectorizer takes an encoding parameter for this purpose. For modern text files, the correct encoding is probably UTF-8, which is therefore the default (encoding="utf-8").

If the text you are loading is not actually encoded with UTF-8, however, you will get a UnicodeDecodeError. The vectorizers can be told to be silent about decoding errors by setting the decode_error parameter to either "ignore" or "replace". See the documentation for the Python function bytes.decode for more details (type help(bytes.decode) at the Python prompt).

Troubleshooting decoding text

If you are having trouble decoding text, here are some things to try:

  • Find out what the actual encoding of the text is. The file might come with a header or README that tells you the encoding, or there might be some standard encoding you can assume based on where the text comes from.

  • You may be able to find out what kind of encoding it is in general using the UNIX command file. The Python chardet module comes with a script called chardetect.py that will guess the specific encoding, though you cannot rely on its guess being correct.

  • You could try UTF-8 and disregard the errors. You can decode byte strings with bytes.decode(errors='replace') to replace all decoding errors with a meaningless character, or set decode_error='replace' in the vectorizer. This may damage the usefulness of your features.

  • Real text may come from a variety of sources that may have used different encodings, or even be sloppily decoded in a different encoding than the one it was encoded with. This is common in text retrieved from the Web. The Python package ftfy can automatically sort out some classes of decoding errors, so you could try decoding the unknown text as latin-1 and then using ftfy to fix errors.

  • If the text is in a mish-mash of encodings that is simply too hard to sort out (which is the case for the 20 Newsgroups dataset), you can fall back on a simple single-byte encoding such as latin-1. Some text may display incorrectly, but at least the same sequence of bytes will always represent the same feature.

For example, the following snippet uses chardet (not shipped with scikit-learn, must be installed separately) to figure out the encoding of three texts. It then vectorizes the texts and prints the learned vocabulary. The output is not shown here.

>>> import chardet
>>> text1 = b"Sei mir gegr\xc3\xbc\xc3\x9ft mein Sauerkraut"
>>> text2 = b"holdselig sind deine Ger\xfcche"
>>> text3 = b"\xff\xfeA\x00u\x00f\x00 \x00F\x00l\x00\xfc\x00g\x00e\x00l\x00n\x00 \x00d\x00e\x00s\x00 \x00G\x00e\x00s\x00a\x00n\x00g\x00e\x00s\x00,\x00 \x00H\x00e\x00r\x00z\x00l\x00i\x00e\x00b\x00c\x00h\x00e\x00n\x00,\x00 \x00t\x00r\x00a\x00g\x00 \x00i\x00c\x00h\x00 \x00d\x00i\x00c\x00h\x00 \x00f\x00o\x00r\x00t\x00"
>>> decoded = [x.decode(chardet.detect(x)['encoding'])
...            for x in (text1, text2, text3)]
>>> v = CountVectorizer().fit(decoded).vocabulary_
>>> for term in v: print(v)

(Depending on the version of chardet, it might get the first one wrong.)

For an introduction to Unicode and character encodings in general, see Joel Spolsky’s Absolute Minimum Every Software Developer Must Know About Unicode.

8.2.3.7. Applications and examples

The bag of words representation is quite simplistic but surprisingly useful in practice.

In particular in a supervised setting it can be successfully combined with fast and scalable linear models to train document classifiers, for instance:

In an unsupervised setting it can be used to group similar documents together by applying clustering algorithms such as K-means:

Finally it is possible to discover the main topics of a corpus by relaxing the hard assignment constraint of clustering, for instance by using Non-negative matrix factorization (NMF or NNMF):

8.2.3.8. Limitations of the Bag of Words representation

A collection of unigrams (what bag of words is) cannot capture phrases and multi-word expressions, effectively disregarding any word order dependence. Additionally, the bag of words model doesn’t account for potential misspellings or word derivations.

N-grams to the rescue! Instead of building a simple collection of unigrams (n=1), one might prefer a collection of bigrams (n=2), where occurrences of pairs of consecutive words are counted.

One might alternatively consider a collection of character n-grams, a representation resilient against misspellings and derivations.

For example, let’s say we’re dealing with a corpus of two documents: ['words', 'wprds']. The second document contains a misspelling of the word ‘words’. A simple bag of words representation would consider these two as very distinct documents, differing in both of the two possible features. A character 2-gram representation, however, would find the documents matching in 4 out of 8 features, which may help the preferred classifier decide better:

>>> ngram_vectorizer = CountVectorizer(analyzer='char_wb', ngram_range=(2, 2))
>>> counts = ngram_vectorizer.fit_transform(['words', 'wprds'])
>>> ngram_vectorizer.get_feature_names_out()
array([' w', 'ds', 'or', 'pr', 'rd', 's ', 'wo', 'wp'], ...)
>>> counts.toarray().astype(int)
array([[1, 1, 1, 0, 1, 1, 1, 0],
       [1, 1, 0, 1, 1, 1, 0, 1]])

In the above example, char_wb analyzer is used, which creates n-grams only from characters inside word boundaries (padded with space on each side). The char analyzer, alternatively, creates n-grams that span across words:

>>> ngram_vectorizer = CountVectorizer(analyzer='char_wb', ngram_range=(5, 5))
>>> ngram_vectorizer.fit_transform(['jumpy fox'])
<Compressed Sparse...dtype 'int64'
  with 4 stored elements and shape (1, 4)>

>>> ngram_vectorizer.get_feature_names_out()
array([' fox ', ' jump', 'jumpy', 'umpy '], ...)

>>> ngram_vectorizer = CountVectorizer(analyzer='char', ngram_range=(5, 5))
>>> ngram_vectorizer.fit_transform(['jumpy fox'])
<Compressed Sparse...dtype 'int64'
  with 5 stored elements and shape (1, 5)>
>>> ngram_vectorizer.get_feature_names_out()
array(['jumpy', 'mpy f', 'py fo', 'umpy ', 'y fox'], ...)

The word boundaries-aware variant char_wb is especially interesting for languages that use white-spaces for word separation as it generates significantly less noisy features than the raw char variant in that case. For such languages it can increase both the predictive accuracy and convergence speed of classifiers trained using such features while retaining the robustness with regards to misspellings and word derivations.

While some local positioning information can be preserved by extracting n-grams instead of individual words, bag of words and bag of n-grams destroy most of the inner structure of the document and hence most of the meaning carried by that internal structure.

In order to address the wider task of Natural Language Understanding, the local structure of sentences and paragraphs should thus be taken into account. Many such models will thus be casted as “Structured output” problems which are currently outside of the scope of scikit-learn.

8.2.3.9. Vectorizing a large text corpus with the hashing trick

The above vectorization scheme is simple but the fact that it holds an in-memory mapping from the string tokens to the integer feature indices (the vocabulary_ attribute) causes several problems when dealing with large datasets:

  • the larger the corpus, the larger the vocabulary will grow and hence the memory use too,

  • fitting requires the allocation of intermediate data structures of size proportional to that of the original dataset.

  • building the word-mapping requires a full pass over the dataset hence it is not possible to fit text classifiers in a strictly online manner.

  • pickling and un-pickling vectorizers with a large vocabulary_ can be very slow (typically much slower than pickling / un-pickling flat data structures such as a NumPy array of the same size),

  • it is not easily possible to split the vectorization work into concurrent sub tasks as the vocabulary_ attribute would have to be a shared state with a fine grained synchronization barrier: the mapping from token string to feature index is dependent on the ordering of the first occurrence of each token hence would have to be shared, potentially harming the concurrent workers’ performance to the point of making them slower than the sequential variant.

It is possible to overcome those limitations by combining the “hashing trick” (Feature hashing) implemented by the FeatureHasher class and the text preprocessing and tokenization features of the CountVectorizer.

This combination is implemented in HashingVectorizer, a transformer class that is mostly API compatible with CountVectorizer. HashingVectorizer is stateless, meaning that you don’t have to call fit on it:

>>> from sklearn.feature_extraction.text import HashingVectorizer
>>> hv = HashingVectorizer(n_features=10)
>>> hv.transform(corpus)
<Compressed Sparse...dtype 'float64'
  with 16 stored elements and shape (4, 10)>

You can see that 16 non-zero feature tokens were extracted in the vector output: this is less than the 19 non-zeros extracted previously by the CountVectorizer on the same toy corpus. The discrepancy comes from hash function collisions because of the low value of the n_features parameter.

In a real world setting, the n_features parameter can be left to its default value of 2 ** 20 (roughly one million possible features). If memory or downstream models size is an issue selecting a lower value such as 2 ** 18 might help without introducing too many additional collisions on typical text classification tasks.

Note that the dimensionality does not affect the CPU training time of algorithms which operate on CSR matrices (LinearSVC(dual=True), Perceptron, SGDClassifier) but it does for algorithms that work with CSC matrices (LinearSVC(dual=False), Lasso(), etc.).

Let’s try again with the default setting:

>>> hv = HashingVectorizer()
>>> hv.transform(corpus)
<Compressed Sparse...dtype 'float64'
  with 19 stored elements and shape (4, 1048576)>

We no longer get the collisions, but this comes at the expense of a much larger dimensionality of the output space. Of course, other terms than the 19 used here might still collide with each other.

The HashingVectorizer also comes with the following limitations:

  • it is not possible to invert the model (no inverse_transform method), nor to access the original string representation of the features, because of the one-way nature of the hash function that performs the mapping.

  • it does not provide IDF weighting as that would introduce statefulness in the model. A TfidfTransformer can be appended to it in a pipeline if required.

Performing out-of-core scaling with HashingVectorizer

An interesting development of using a HashingVectorizer is the ability to perform out-of-core scaling. This means that we can learn from data that does not fit into the computer’s main memory.

A strategy to implement out-of-core scaling is to stream data to the estimator in mini-batches. Each mini-batch is vectorized using HashingVectorizer so as to guarantee that the input space of the estimator has always the same dimensionality. The amount of memory used at any time is thus bounded by the size of a mini-batch. Although there is no limit to the amount of data that can be ingested using such an approach, from a practical point of view the learning time is often limited by the CPU time one wants to spend on the task.

For a full-fledged example of out-of-core scaling in a text classification task see Out-of-core classification of text documents.

8.2.3.10. Customizing the vectorizer classes

It is possible to customize the behavior by passing a callable to the vectorizer constructor:

>>> def my_tokenizer(s):
...     return s.split()
...
>>> vectorizer = CountVectorizer(tokenizer=my_tokenizer)
>>> vectorizer.build_analyzer()(u"Some... punctuation!") == (
...     ['some...', 'punctuation!'])
True

In particular we name:

  • preprocessor: a callable that takes an entire document as input (as a single string), and returns a possibly transformed version of the document, still as an entire string. This can be used to remove HTML tags, lowercase the entire document, etc.

  • tokenizer: a callable that takes the output from the preprocessor and splits it into tokens, then returns a list of these.

  • analyzer: a callable that replaces the preprocessor and tokenizer. The default analyzers all call the preprocessor and tokenizer, but custom analyzers will skip this. N-gram extraction and stop word filtering take place at the analyzer level, so a custom analyzer may have to reproduce these steps.

(Lucene users might recognize these names, but be aware that scikit-learn concepts may not map one-to-one onto Lucene concepts.)

To make the preprocessor, tokenizer and analyzers aware of the model parameters it is possible to derive from the class and override the build_preprocessor, build_tokenizer and build_analyzer factory methods instead of passing custom functions.

Tips and tricks
  • If documents are pre-tokenized by an external package, then store them in files (or strings) with the tokens separated by whitespace and pass analyzer=str.split

  • Fancy token-level analysis such as stemming, lemmatizing, compound splitting, filtering based on part-of-speech, etc. are not included in the scikit-learn codebase, but can be added by customizing either the tokenizer or the analyzer. Here’s a CountVectorizer with a tokenizer and lemmatizer using NLTK:

    >>> from nltk import word_tokenize
    >>> from nltk.stem import WordNetLemmatizer
    >>> class LemmaTokenizer:
    ...     def __init__(self):
    ...         self.wnl = WordNetLemmatizer()
    ...     def __call__(self, doc):
    ...         return [self.wnl.lemmatize(t) for t in word_tokenize(doc)]
    ...
    >>> vect = CountVectorizer(tokenizer=LemmaTokenizer())
    

    (Note that this will not filter out punctuation.)

    The following example will, for instance, transform some British spelling to American spelling:

    >>> import re
    >>> def to_british(tokens):
    ...     for t in tokens:
    ...         t = re.sub(r"(...)our$", r"\1or", t)
    ...         t = re.sub(r"([bt])re$", r"\1er", t)
    ...         t = re.sub(r"([iy])s(e$|ing|ation)", r"\1z\2", t)
    ...         t = re.sub(r"ogue$", "og", t)
    ...         yield t
    ...
    >>> class CustomVectorizer(CountVectorizer):
    ...     def build_tokenizer(self):
    ...         tokenize = super().build_tokenizer()
    ...         return lambda doc: list(to_british(tokenize(doc)))
    ...
    >>> print(CustomVectorizer().build_analyzer()(u"color colour"))
    [...'color', ...'color']
    

    for other styles of preprocessing; examples include stemming, lemmatization, or normalizing numerical tokens, with the latter illustrated in:

Customizing the vectorizer can also be useful when handling Asian languages that do not use an explicit word separator such as whitespace.

8.2.4. Image feature extraction

8.2.4.1. Patch extraction

The extract_patches_2d function extracts patches from an image stored as a two-dimensional array, or three-dimensional with color information along the third axis. For rebuilding an image from all its patches, use reconstruct_from_patches_2d. For example let us generate a 4x4 pixel picture with 3 color channels (e.g. in RGB format):

>>> import numpy as np
>>> from sklearn.feature_extraction import image

>>> one_image = np.arange(4 * 4 * 3).reshape((4, 4, 3))
>>> one_image[:, :, 0]  # R channel of a fake RGB picture
array([[ 0,  3,  6,  9],
       [12, 15, 18, 21],
       [24, 27, 30, 33],
       [36, 39, 42, 45]])

>>> patches = image.extract_patches_2d(one_image, (2, 2), max_patches=2,
...     random_state=0)
>>> patches.shape
(2, 2, 2, 3)
>>> patches[:, :, :, 0]
array([[[ 0,  3],
        [12, 15]],

       [[15, 18],
        [27, 30]]])
>>> patches = image.extract_patches_2d(one_image, (2, 2))
>>> patches.shape
(9, 2, 2, 3)
>>> patches[4, :, :, 0]
array([[15, 18],
       [27, 30]])

Let us now try to reconstruct the original image from the patches by averaging on overlapping areas:

>>> reconstructed = image.reconstruct_from_patches_2d(patches, (4, 4, 3))
>>> np.testing.assert_array_equal(one_image, reconstructed)

The PatchExtractor class works in the same way as extract_patches_2d, only it supports multiple images as input. It is implemented as a scikit-learn transformer, so it can be used in pipelines. See:

>>> five_images = np.arange(5 * 4 * 4 * 3).reshape(5, 4, 4, 3)
>>> patches = image.PatchExtractor(patch_size=(2, 2)).transform(five_images)
>>> patches.shape
(45, 2, 2, 3)

8.2.4.2. Connectivity graph of an image

Several estimators in scikit-learn can use connectivity information between features or samples. For instance Ward clustering (Hierarchical clustering) can cluster together only neighboring pixels of an image, thus forming contiguous patches:

../_images/sphx_glr_plot_coin_ward_segmentation_001.png

For this purpose, the estimators use a ‘connectivity’ matrix, giving which samples are connected.

The function img_to_graph returns such a matrix from a 2D or 3D image. Similarly, grid_to_graph builds a connectivity matrix for images given the shape of these images.

These matrices can be used to impose connectivity in estimators that use connectivity information, such as Ward clustering (Hierarchical clustering), but also to build precomputed kernels, or similarity matrices.

LLM02:2025 Sensitive Information Disclosure

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.

LLM02:2025 Sensitive Information Disclosure

Sensitive information can affect both the LLM and its application context. This includes personal identifiable information (PII), financial details, health records, confidential business data, security credentials, and legal documents. Proprietary models may also have unique training methods and source code considered sensitive, especially in closed or foundation models.

LLMs, especially when embedded in applications, risk exposing sensitive data, proprietary algorithms, or confidential details through their output. This can result in unauthorized data access, privacy violations, and intellectual property breaches. Consumers should be aware of how to interact safely with LLMs. They need to understand the risks of unintentionally providing sensitive data, which may later be disclosed in the model’s output.

To reduce this risk, LLM applications should perform adequate data sanitization to prevent user data from entering the training model. Application owners should also provide clear Terms of Use policies, allowing users to opt out of having their data included in the training model. Adding restrictions within the system prompt about data types that the LLM should return can provide mitigation against sensitive information disclosure. However, such restrictions may not always be honored and could be bypassed via prompt injection or other methods.

Personal identifiable information (PII) may be disclosed during interactions with the LLM.

Poorly configured model outputs can reveal proprietary algorithms or data. Revealing training data can expose models to inversion attacks, where attackers extract sensitive information or reconstruct inputs. For instance, as demonstrated in the ‘Proof Pudding’ attack (CVE-2019-20634), disclosed training data facilitated model extraction and inversion, allowing attackers to circumvent security controls in machine learning algorithms and bypass email filters.

Generated responses might inadvertently include confidential business information.

###@ Sanitization:

Implement data sanitization to prevent user data from entering the training model. This includes scrubbing or masking sensitive content before it is used in training.

Apply strict input validation methods to detect and filter out potentially harmful or sensitive data inputs, ensuring they do not compromise the model.

###@ Access Controls:

Limit access to sensitive data based on the principle of least privilege. Only grant access to data that is necessary for the specific user or process.

Limit model access to external data sources, and ensure runtime data orchestration is securely managed to avoid unintended data leakage.

###@ Federated Learning and Privacy Techniques:

Train models using decentralized data stored across multiple servers or devices. This approach minimizes the need for centralized data collection and reduces exposure risks.

Apply techniques that add noise to the data or outputs, making it difficult for attackers to reverse-engineer individual data points.

###@ User Education and Transparency:

Provide guidance on avoiding the input of sensitive information. Offer training on best practices for interacting with LLMs securely.

Maintain clear policies about data retention, usage, and deletion. Allow users to opt out of having their data included in training processes.

###@ Secure System Configuration:

Limit the ability for users to override or access the system’s initial settings, reducing the risk of exposure to internal configurations.

Follow guidelines like “OWASP API8:2023 Security Misconfiguration” to prevent leaking sensitive information through error messages or configuration details. (Ref. link:OWASP API8:2023 Security Misconfiguration)

###@ Advanced Techniques:

Use homomorphic encryption to enable secure data analysis and privacy-preserving machine learning. This ensures data remains confidential while being processed by the model.

Implement tokenization to preprocess and sanitize sensitive information. Techniques like pattern matching can detect and redact confidential content before processing.

A user receives a response containing another user’s personal data due to inadequate data sanitization.

An attacker bypasses input filters to extract sensitive information.

Negligent data inclusion in training leads to sensitive information disclosure.

  1. Lessons learned from ChatGPT’s Samsung leak: Cybernews
  2. AI data leak crisis: New tool prevents company secrets from being fed to ChatGPT: Fox Business
  3. ChatGPT Spit Out Sensitive Data When Told to Repeat ‘Poem’ Forever: Wired
  4. Using Differential Privacy to Build Secure Models: Neptune Blog
  5. Proof Pudding (CVE-2019-20634) AVID (moohax & monoxgas)

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 7: Sessions framework

    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 7: Sessions framework

    This tutorial extends our LocalLibrary website, adding a session-based visit-counter to the home page. This is a relatively simple example, but it does show how you can use the session framework to provide persistent behavior for anonymous users in your own sites.

    Prerequisites: Complete all previous tutorial topics, including Django Tutorial Part 6: Generic list and detail views
    Objective: To understand how sessions are used.

    Overview

    The LocalLibrary website we created in the previous tutorials allows users to browse books and authors in the catalog. While the content is dynamically generated from the database, every user will essentially have access to the same pages and types of information when they use the site.

    In a "real" library you may wish to provide individual users with a customized experience, based on their previous use of the site, preferences, etc. For example, you could hide warning messages that the user has previously acknowledged next time they visit the site, or store and respect their preferences (such as, the number of search results that they want to be displayed on each page).

    The session framework lets you implement this sort of behavior, allowing you to store and retrieve arbitrary data on a per-site-visitor basis.

    What are sessions?

    All communication between web browsers and servers is via HTTP, which is stateless. The fact that the protocol is stateless means that messages between the client and server are completely independent of each other — there is no notion of "sequence" or behavior based on previous messages. As a result, if you want to have a site that keeps track of the ongoing relationships with a client, you need to implement that yourself.

    Sessions are the mechanism used by Django (and most of the Internet) for keeping track of the "state" between the site and a particular browser. Sessions allow you to store arbitrary data per browser, and have this data available to the site whenever the browser connects. Individual data items associated with the session are then referenced by a "key", which is used both to store and retrieve the data.

    Django uses a cookie containing a special session id to identify each browser and its associated session with the site. The actual session data is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users). You can configure Django to store the session data in other places (cache, files, "secure" cookies), but the default location is a good and relatively secure option.

    Enabling sessions

    Sessions were enabled automatically when we created the skeleton website (in tutorial 2).

    The configuration is set up in the INSTALLED_APPS and MIDDLEWARE sections of the project file (django-locallibrary-tutorial/locallibrary/settings.py), as shown below:

    python
    INSTALLED_APPS = [
        # …
        'django.contrib.sessions',
        # …
    
    MIDDLEWARE = [
        # …
        'django.contrib.sessions.middleware.SessionMiddleware',
        # …
    

    Using sessions

    You can access the session attribute within a view from the request parameter (an HttpRequest passed in as the first argument to the view). This session attribute represents the specific connection to the current user (or to be more precise, the connection to the current browser, as identified by the session id in the browser's cookie for this site).

    The session attribute is a dictionary-like object that you can read and write as many times as you like in your view, modifying it as wished. You can do all the normal dictionary operations, including clearing all data, testing if a key is present, looping through data, etc. Most of the time though, you'll just use the standard "dictionary" API to get and set values.

    The code fragments below show how you can get, set, and delete some data with the key my_car, associated with the current session (browser).

    Note: One of the great things about Django is that you don't need to think about the mechanisms that tie the session to your current request in your view. If we were to use the fragments below in our view, we'd know that the information about my_car is associated only with the browser that sent the current request.

    python
    # Get a session value by its key (e.g. 'my_car'), raising a KeyError if the key is not present
    my_car = request.session['my_car']
    
    # Get a session value, setting a default if it is not present ('mini')
    my_car = request.session.get('my_car', 'mini')
    
    # Set a session value
    request.session['my_car'] = 'mini'
    
    # Delete a session value
    del request.session['my_car']
    

    The API also offers a number of other methods that are mostly used to manage the associated session cookie. For example, there are methods to test that cookies are supported in the client browser, to set and check cookie expiry dates, and to clear expired sessions from the data store. You can find out about the full API in How to use sessions (Django docs).

    Saving session data

    By default, Django only saves to the session database and sends the session cookie to the client when the session has been modified (assigned) or deleted. If you're updating some data using its session key as shown in the previous section, then you don't need to worry about this! For example:

    python
    # This is detected as an update to the session, so session data is saved.
    request.session['my_car'] = 'mini'
    

    If you're updating some information within session data, then Django will not recognize that you've made a change to the session and save the data (for example, if you were to change wheels data inside your my_car data, as shown below). In this case you will need to explicitly mark the session as having been modified.

    python
    # Session object not directly modified, only data within the session. Session changes not saved!
    request.session['my_car']['wheels'] = 'alloy'
    
    # Set session as modified to force data updates/cookie to be saved.
    request.session.modified = True
    

    Note: You can change the behavior so the site will update the database/send cookie on every request by adding SESSION_SAVE_EVERY_REQUEST = True into your project settings (django-locallibrary-tutorial/locallibrary/settings.py).

    Simple example — getting visit counts

    As a simple real-world example we'll update our library to tell the current user how many times they have visited the LocalLibrary home page.

    Open /django-locallibrary-tutorial/catalog/views.py, and add the lines that contain num_visits into index() (as shown below).

    python
    def index(request):
        # …
    
        num_authors = Author.objects.count()  # The 'all()' is implied by default.
    
        # Number of visits to this view, as counted in the session variable.
        num_visits = request.session.get('num_visits', 0)
        num_visits += 1
        request.session['num_visits'] = num_visits
    
        context = {
            'num_books': num_books,
            'num_instances': num_instances,
            'num_instances_available': num_instances_available,
            'num_authors': num_authors,
            'num_visits': num_visits,
        }
    
        # Render the HTML template index.html with the data in the context variable.
        return render(request, 'index.html', context=context)
    

    Here we first get the value of the 'num_visits' session key, setting the value to 0 if it has not previously been set. Each time a request is received, we then increment the value and store it back in the session (for the next time the user visits the page). The num_visits variable is then passed to the template in our context variable.

    Note: We might also test whether cookies are even supported in the browser here (see How to use sessions for examples) or design our UI so that it doesn't matter whether or not cookies are supported.

    Add the line shown at the bottom of the following block to your main HTML template (/django-locallibrary-tutorial/catalog/templates/index.html) at the bottom of the "Dynamic content" section to display the num_visits context variable.

    django
    <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>
    
    <p>
      You have visited this page {{ num_visits }} time{{ num_visits|pluralize }}.
    </p>
    

    Note that we use the Django built-in template tag pluralize to add an "s" when the page has been visited multiple times.

    Save your changes and restart the test server. Every time you refresh the page, the number should update.

    Summary

    You now know how easy it is to use sessions to improve your interaction with anonymous users.

    In our next articles we'll explain the authentication and authorization (permission) framework, and show you how to support user accounts.

    See also