Complete Assigned Readings

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

5. Data Structures

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.

5. Data Structures

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.

5.1. More on Lists

The list data type has some more methods. Here are all of the methods of list objects:

list.append(value, /)

Add an item to the end of the list. Similar to a[len(a):] = [x].

list.extend(iterable, /)

Extend the list by appending all the items from the iterable. Similar to a[len(a):] = iterable.

list.insert(index, value, /)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.remove(value, /)

Remove the first item from the list whose value is equal to value. It raises a ValueError if there is no such item.

list.pop(index=-1, /)

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. It raises an IndexError if the list is empty or the index is outside the list range.

list.clear()

Remove all items from the list. Similar to del a[:].

list.index(value[, start[, stop]])

Return zero-based index of the first occurrence of value in the list. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

list.count(value, /)

Return the number of times value appears in the list.

list.sort(*, key=None, reverse=False)

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

list.reverse()

Reverse the elements of the list in place.

list.copy()

Return a shallow copy of the list. Similar to a[:].

An example that uses most of the list methods:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting at position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. [1] This is a design principle for all mutable data structures in Python.

Another thing you might notice is that not all data can be sorted or compared. For instance, [None, 'hello', 10] doesn’t sort because integers can’t be compared to strings and None can’t be compared to other types. Also, there are some types that don’t have a defined ordering relation. For example, 3+4j < 5+7j isn’t a valid comparison.

5.1.1. Using Lists as Stacks

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

5.1.2. Using Lists as Queues

It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one). See Time complexity of operations on built-in types for more information.

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

5.1.3. List Comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:

squares = list(map(lambda x: x**2, range(10)))

or, equivalently:

squares = [x**2 for x in range(10)]

which is more concise and readable.

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

and it’s equivalent to:

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Note how the order of the for and if statements is the same in both these snippets.

If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.

>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
  File "<stdin>", line 1
    [x, x**2 for x in range(6)]
     ^^^^^^^
SyntaxError: did you forget parentheses around the comprehension target?
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehensions can contain complex expressions and nested functions:

>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

5.1.4. Nested List Comprehensions

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

The following list comprehension will transpose rows and columns:

>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

As we saw in the previous section, the inner list comprehension is evaluated in the context of the for that follows it, so this example is equivalent to:

>>> transposed = []
>>> for i in range(4):
...     transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

which, in turn, is the same as:

>>> transposed = []
>>> for i in range(4):
...     # the following 3 lines implement the nested listcomp
...     transposed_row = []
...     for row in matrix:
...         transposed_row.append(row[i])
...     transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:

>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

See Unpacking Argument Lists for details on the asterisk in this line.

5.1.5. Unpacking in Lists and List Comprehensions

The section on Unpacking Argument Lists describes the use of * to “unpack” the elements of an iterable object, providing each one separately as an argument to a function. Unpacking can also be used in other contexts, for example, when creating lists. When specifying elements of a list, prefixing an expression by a * will unpack the result of that expression, adding each of its elements to the list we’re creating:

>>> x = [1, 2, 3]
>>> [0, *x, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]

This only works if the expression following the * evaluates to an iterable object; trying to unpack a non-iterable object will raise an exception:

>>> x = 1
>>> [0, *x, 2, 3, 4]
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    [0, *x, 2, 3, 4]
TypeError: Value after * must be an iterable, not int

Unpacking can also be used in list comprehensions, as a way to build a new list representing the concatenation of an arbitrary number of iterables:

>>> x = [[1, 2, 3], [4, 5, 6], [], [7], [8, 9]]
>>> [*element for element in x]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Note that the effect is that each element from x is unpacked. This works for arbitrary iterable objects, not just lists:

>>> x = [[1, 2, 3], 'cat', {'spam': 'eggs'}]
>>> [*element for element in x]
[1, 2, 3, 'c', 'a', 't', 'spam']

But if the objects in x are not iterable, this expression would again raise an exception.

5.2. The del statement

There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

del can also be used to delete entire variables:

>>> del a

Referencing the name a hereafter is an error (at least until another value is assigned to it). We’ll find other uses for del later.

5.3. Tuples and Sequences

We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.

A tuple consists of a number of values separated by commas, for instance:

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
>>> u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
>>> t[0] = 88888
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
>>> v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
>>> # they support unpacking just like lists:
>>> x = [1, 2, 3]
>>> 0, *x, 4
(0, 1, 2, 3, 4)

As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:

>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

>>> x, y, z = t

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

5.4. Sets

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

Because sets are unordered, iterating over them or printing them can produce the elements in a different order than you expect.

Here is a brief demonstration:

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # fast membership testing
True
>>> 'crabgrass' in basket
False

>>> # Demonstrate set operations on unique letters from two words
>>>
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}

Similarly to list comprehensions, set comprehensions are also supported, including comprehensions with unpacking:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

>>> fruits = [{'apple', 'avocado', 'apricot'}, {'banana', 'blueberry'}]
>>> {*fruit for fruit in fruits}
{'blueberry', 'banana', 'avocado', 'apple', 'apricot'}

5.5. Dictionaries

Another useful data type built into Python is the dictionary (see Mapping types — dict, frozendict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten.

Extracting a value for a non-existent key by subscripting (d[key]) raises a KeyError. To avoid getting this error when trying to access a possibly non-existent key, use the get() method instead, which returns None (or a specified default value) if the key is not in the dictionary.

Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.

Here is a small example using a dictionary:

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> tel['irv']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'irv'
>>> print(tel.get('irv'))
None
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

And dictionary unpacking (via **) can be used to merge multiple dictionaries:

>>> odds = {i: i**2 for i in (1, 3, 5)}
>>> evens = {i: i**2 for i in (2, 4, 6)}
>>> {**odds, **evens}
{1: 1, 3: 9, 5: 25, 2: 4, 4: 16, 6: 36}

>>> all_values = [odds, evens, {0: 0}]
>>> {**i for i in all_values}
{1: 1, 3: 9, 5: 25, 2: 4, 4: 16, 6: 36, 0: 0}

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}

5.6. Looping Techniques

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for i in sorted(basket):
...     print(i)
...
apple
apple
banana
orange
orange
pear

Using set() on a sequence eliminates duplicate elements. The use of sorted() in combination with set() over a sequence is an idiomatic way to loop over unique elements of the sequence in sorted order.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
...     if not math.isnan(value):
...         filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]

5.7. More on Conditions

The conditions used in while and if statements can contain any operators, not just comparisons.

The comparison operators in and not in are membership tests that determine whether a value is in (or not in) a container. The operators is and is not compare whether two objects are really the same object. All comparison operators have the same priority, which is lower than that of all numerical operators.

Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c.

Comparisons may be combined using the Boolean operators and and or, and the outcome of a comparison (or of any other Boolean expression) may be negated with not. These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C. As always, parentheses can be used to express the desired composition.

The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.

It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

Note that in Python, unlike C, assignment inside expressions must be done explicitly with the walrus operator :=. This avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.

5.8. Comparing Sequences and Other Types

Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:

(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)

Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.

Footnotes

2 . Array-Based Lists

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

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

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


2. Array-Based Lists

In this chapter, we will study implementations of the List and Queue interfaces where the underlying data is stored in an array, called the backing array. The following table summarizes the running times of operations for the data structures presented in this chapter:


  $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$/ $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$/ $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$
ArrayStack $ O(1)$ $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}})$
ArrayDeque $ O(1)$ $ O(\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$
DualArrayDeque $ O(1)$ $ O(\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$
RootishArrayStack $ O(1)$ $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}})$

Data structures that work by storing data in a single array have many advantages and limitations in common: The third point is important. The running times cited in the table above do not include the cost associated with growing and shrinking the backing array. We will see that, if carefully managed, the cost of growing and shrinking the backing array does not add much to the cost of an average operation. More precisely, if we start with an empty data structure, and perform any sequence of $ m$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operations, then the total cost of growing and shrinking the backing array, over the entire sequence of $ m$ operations is $ O(m)$. Although some individual operations are more expensive, the amortized cost, when amortized over all $ m$ operations, is only $ O(1)$ per operation.



Subsections
opendatastructures.org

5 . Hash Tables

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.


5. Hash Tables

Hash tables are an efficient method of storing a small number, $ \ensuremath{\ensuremath{\mathit{n}}}$, of integers from a large range $ U=\{0,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1\}$. The term hash table includes a broad range of data structures. The first part of this chapter focuses on two of the most common implementations of hash tables: hashing with chaining and linear probing.

Very often hash tables store types of data that are not integers. In this case, an integer hash code is associated with each data item and is used in the hash table. The second part of this chapter discusses how such hash codes are generated.

Some of the methods used in this chapter require random choices of integers in some specific range. In the code samples, some of these ``random'' integers are hard-coded constants. These constants were obtained using random bits generated from atmospheric noise.



Subsections

opendatastructures.org

6 . 3 Discussion and Exercises

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

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

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

6.3 Discussion and Exercises

Binary trees have been used to model relationships for thousands of years. One reason for this is that binary trees naturally model (pedigree) family trees. These are the family trees in which the root is a person, the left and right children are the person's parents, and so on, recursively. In more recent centuries binary trees have also been used to model species trees in biology, where the leaves of the tree represent extant species and the internal nodes of the tree represent speciation events in which two populations of a single species evolve into two separate species.

Binary search trees appear to have been discovered independently by several groups in the 1950s [48, Section 6.2.2]. Further references to specific kinds of binary search trees are provided in subsequent chapters.

When implementing a binary tree from scratch, there are several design decisions to be made. One of these is the question of whether or not each node stores a pointer to its parent. If most of the operations simply follow a root-to-leaf path, then parent pointers are unnecessary, waste space, and are a potential source of coding errors. On the other hand, the lack of parent pointers means that tree traversals must be done recursively or with the use of an explicit stack. Some other methods (like inserting or deleting into some kinds of balanced binary search trees) are also complicated by the lack of parent pointers.

Another design decision is concerned with how to store the parent, left child, and right child pointers at a node. In the implementation given here, these pointers are stored as separate variables. Another option is to store them in an array, $ \ensuremath{\ensuremath{\mathit{p}}}$, of length 3, so that $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}[0]}$ is the left child of $ \ensuremath{\ensuremath{\mathit{u}}}$, $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}[1]}$ is the right child of $ \ensuremath{\ensuremath{\mathit{u}}}$, and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}[2]}$ is the parent of $ \ensuremath{\ensuremath{\mathit{u}}}$. Using an array this way means that some sequences of $ {\color{black} \textbf{if}}$ statements can be simplified into algebraic expressions.

An example of such a simplification occurs during tree traversal. If a traversal arrives at a node $ \ensuremath{\ensuremath{\mathit{u}}}$ from $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}[\ensuremath{\mathit{i}}]}$, then the next node in the traversal is $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}}}[(\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+1)\bmod 3]$. Similar examples occur when there is left-right symmetry. For example, the sibling of $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}[\ensuremath{\mathit{i}}]}$ is $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}}}[(\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+1)\bmod 2]$. This trick works whether $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{p}}[\ensuremath{\mathit{i}}]}$ is a left child ( $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}=0$) or a right child ( $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}=1$) of $ \ensuremath{\ensuremath{\mathit{u}}}$. In some cases this means that some complicated code that would otherwise need to have both a left version and right version can be written only once. See the methods $ \ensuremath{\mathrm{rotate\_left}(\ensuremath{\mathit{u}})}$ and $ \ensuremath{\mathrm{rotate\_right}(\ensuremath{\mathit{u}})}$ on page [*] for an example.

Exercise 6..1   Prove that a binary tree having $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\ge 1$ nodes has $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1$ edges.

Exercise 6..2   Prove that a binary tree having $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\ge 1$ real nodes has $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+1$ external nodes.

Exercise 6..3   Prove that, if a binary tree, $ T$, has at least one leaf, then either (a) $ T$'s root has at most one child or (b) $ T$ has more than one leaf.

Exercise 6..4   Implement a non-recursive method, $ \ensuremath{\mathrm{size2}(\ensuremath{\mathit{u}})}$, that computes the size of the subtree rooted at node $ \ensuremath{\ensuremath{\mathit{u}}}$.

Exercise 6..5   Write a non-recursive method, $ \ensuremath{\mathrm{height2}(\ensuremath{\mathit{u}})}$, that computes the height of node $ \ensuremath{\ensuremath{\mathit{u}}}$ in a BinaryTree.

Exercise 6..6   A binary tree is size-balanced if, for every node $ \ensuremath{\ensuremath{\mathit{u}}}$, the size of the subtrees rooted at $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}}$ and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$ differ by at most one. Write a recursive method, $ \ensuremath{\mathrm{is\_balanced}()}$, that tests if a binary tree is balanced. Your method should run in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time. (Be sure to test your code on some large trees with different shapes; it is easy to write a method that takes much longer than $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time.)

A pre-order traversal of a binary tree is a traversal that visits each node, $ \ensuremath{\ensuremath{\mathit{u}}}$, before any of its children. An in-order traversal visits $ \ensuremath{\ensuremath{\mathit{u}}}$ after visiting all the nodes in $ \ensuremath{\ensuremath{\mathit{u}}}$'s left subtree but before visiting any of the nodes in $ \ensuremath{\ensuremath{\mathit{u}}}$'s right subtree. A post-order traversal visits $ \ensuremath{\ensuremath{\mathit{u}}}$ only after visiting all other nodes in $ \ensuremath{\ensuremath{\mathit{u}}}$'s subtree. The pre/in/post-order numbering of a tree labels the nodes of a tree with the integers $ 0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1$ in the order that they are encountered by a pre/in/post-order traversal. See Figure 6.10 for an example.

Figure 6.10: Pre-order, post-order, and in-order numberings of a binary tree.
\includegraphics[scale=0.90909]{figs-python/binarytree-numbering-1} \includegraphics[scale=0.90909]{figs-python/binarytree-numbering-2}


\includegraphics[scale=0.90909]{figs-python/binarytree-numbering-3}

Exercise 6..7   Create a subclass of BinaryTree whose nodes have fields for storing pre-order, post-order, and in-order numbers. Write recursive methods $ \ensuremath{\mathrm{pre\_order\mathrm{Number}}()}$, $ \ensuremath{\mathrm{in\_order\mathrm{Number}}()}$, and $ \ensuremath{\mathrm{post\_order\mathrm{Numbers}}()}$ that assign these numbers correctly. These methods should each run in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time.

Exercise 6..8   Implement the non-recursive functions $ \ensuremath{\mathrm{next\_pre\mathrm{Order}}(\ensuremath{\mathit{u}})}$, $ \ensuremath{\mathrm{next\_in\mathrm{Order}}(\ensuremath{\mathit{u}})}$, and $ \ensuremath{\mathrm{next\_post\mathrm{Order}}(\ensuremath{\mathit{u}})}$ that return the node that follows $ \ensuremath{\ensuremath{\mathit{u}}}$ in a pre-order, in-order, or post-order traversal, respectively. These functions should take amortized constant time; if we start at any node $ \ensuremath{\ensuremath{\mathit{u}}}$ and repeatedly call one of these functions and assign the return value to $ \ensuremath{\ensuremath{\mathit{u}}}$ until $ \ensuremath{\ensuremath{\ensuremath{\mathit{u}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{nil}}}}$, then the cost of all these calls should be $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$.

Exercise 6..9   Suppose we are given a binary tree with pre-, post-, and in-order numbers assigned to the nodes. Show how these numbers can be used to answer each of the following questions in constant time:
  1. Given a node $ \ensuremath{\ensuremath{\mathit{u}}}$, determine the size of the subtree rooted at $ \ensuremath{\ensuremath{\mathit{u}}}$.
  2. Given a node $ \ensuremath{\ensuremath{\mathit{u}}}$, determine the depth of $ \ensuremath{\ensuremath{\mathit{u}}}$.
  3. Given two nodes $ \ensuremath{\ensuremath{\mathit{u}}}$ and $ \ensuremath{\ensuremath{\mathit{w}}}$, determine if $ \ensuremath{\ensuremath{\mathit{u}}}$ is an ancestor of $ \ensuremath{\ensuremath{\mathit{w}}}$

Exercise 6..10   Suppose you are given a list of nodes with pre-order and in-order numbers assigned. Prove that there is at most one possible tree with this pre-order/in-order numbering and show how to construct it.

Exercise 6..11   Show that the shape of any binary tree on $ \ensuremath{\ensuremath{\mathit{n}}}$ nodes can be represented using at most $ 2(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1)$ bits. (Hint: think about recording what happens during a traversal and then playing back that recording to reconstruct the tree.)

Exercise 6..12   Illustrate what happens when we add the values $ 3.5$ and then 4.5 to the binary search tree in Figure 6.5.

Exercise 6..13   Illustrate what happens when we remove the values $ 3$ and then 5 from the binary search tree in Figure 6.5.

Exercise 6..14   Implement a BinarySearchTree method, $ \ensuremath{\mathrm{get\_lE}(\ensuremath{\mathit{x}})}$, that returns a list of all items in the tree that are less than or equal to $ \ensuremath{\ensuremath{\mathit{x}}}$. The running time of your method should be $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}'+\ensuremath{\ensuremath{\ensuremath{\mathit{h}}}})$ where $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}'$ is the number of items less than or equal to $ \ensuremath{\ensuremath{\mathit{x}}}$ and $ \ensuremath{\ensuremath{\mathit{h}}}$ is the height of the tree.

Exercise 6..15   Describe how to add the elements $ \{1,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\}$ to an initially empty BinarySearchTree in such a way that the resulting tree has height $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1$. How many ways are there to do this?

Exercise 6..16   If we have some BinarySearchTree and perform the operations $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ followed by $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ (with the same value of $ \ensuremath{\ensuremath{\mathit{x}}}$) do we necessarily return to the original tree?

Exercise 6..17   Can a $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation increase the height of any node in a BinarySearchTree? If so, by how much?

Exercise 6..18   Can an $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation increase the height of any node in a BinarySearchTree? Can it increase the height of the tree? If so, by how much?

Exercise 6..19   Design and implement a version of BinarySearchTree in which each node, $ \ensuremath{\ensuremath{\mathit{u}}}$, maintains values $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{size}}}$ (the size of the subtree rooted at $ \ensuremath{\ensuremath{\mathit{u}}}$), $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{depth}}}$ (the depth of $ \ensuremath{\ensuremath{\mathit{u}}}$), and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{height}}}$ (the height of the subtree rooted at $ \ensuremath{\ensuremath{\mathit{u}}}$).

These values should be maintained, even during calls to the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations, but this should not increase the cost of these operations by more than a constant factor.

opendatastructures.org

12 . 3 Graph Traversal

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

12.3 Graph Traversal

In this section we present two algorithms for exploring a graph, starting at one of its vertices, $ \ensuremath{\ensuremath{\mathit{i}}}$, and finding all vertices that are reachable from $ \ensuremath{\ensuremath{\mathit{i}}}$. Both of these algorithms are best suited to graphs represented using an adjacency list representation. Therefore, when analyzing these algorithms we will assume that the underlying representation is an AdjacencyLists.

12.3.1 Breadth-First Search

The bread-first-search algorithm starts at a vertex $ \ensuremath{\ensuremath{\mathit{i}}}$ and visits, first the neighbours of $ \ensuremath{\ensuremath{\mathit{i}}}$, then the neighbours of the neighbours of $ \ensuremath{\ensuremath{\mathit{i}}}$, then the neighbours of the neighbours of the neighbours of $ \ensuremath{\ensuremath{\mathit{i}}}$, and so on.

This algorithm is a generalization of the breadth-first traversal algorithm for binary trees (Section 6.1.2), and is very similar; it uses a queue, $ \ensuremath{\ensuremath{\mathit{q}}}$, that initially contains only $ \ensuremath{\ensuremath{\mathit{i}}}$. It then repeatedly extracts an element from $ \ensuremath{\ensuremath{\mathit{q}}}$ and adds its neighbours to $ \ensuremath{\ensuremath{\mathit{q}}}$, provided that these neighbours have never been in $ \ensuremath{\ensuremath{\mathit{q}}}$ before. The only major difference between the breadth-first-search algorithm for graphs and the one for trees is that the algorithm for graphs has to ensure that it does not add the same vertex to $ \ensuremath{\ensuremath{\mathit{q}}}$ more than once. It does this by using an auxiliary boolean array, $ \ensuremath{\ensuremath{\mathit{seen}}}$, that tracks which vertices have already been discovered.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{bfs}(\ensure...
...] \gets \ensuremath{\ensuremath{\mathit{true}}}}\\
\end{flushleft}\end{leftbar}
An example of running $ \ensuremath{\mathrm{bfs}(\ensuremath{\mathit{g}},0)}$ on the graph from Figure 12.1 is shown in Figure 12.4. Different executions are possible, depending on the ordering of the adjacency lists; Figure 12.4 uses the adjacency lists in Figure 12.3.

Figure 12.4: An example of bread-first-search starting at node 0. Nodes are labelled with the order in which they are added to $ \ensuremath{\ensuremath{\mathit{q}}}$. Edges that result in nodes being added to $ \ensuremath{\ensuremath{\mathit{q}}}$ are drawn in black, other edges are drawn in grey.
\includegraphics[scale=0.90909]{figs-python/graph-bfs}

Analyzing the running-time of the $ \ensuremath{\mathrm{bfs}(\ensuremath{\mathit{g}},\ensuremath{\mathit{i}})}$ routine is fairly straightforward. The use of the $ \ensuremath{\ensuremath{\mathit{seen}}}$ array ensures that no vertex is added to $ \ensuremath{\ensuremath{\mathit{q}}}$ more than once. Adding (and later removing) each vertex from $ \ensuremath{\ensuremath{\mathit{q}}}$ takes constant time per vertex for a total of $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time. Since each vertex is processed by the inner loop at most once, each adjacency list is processed at most once, so each edge of $ G$ is processed at most once. This processing, which is done in the inner loop takes constant time per iteration, for a total of $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{m}}}})$ time. Therefore, the entire algorithm runs in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{m}}}})$ time.

The following theorem summarizes the performance of the $ \ensuremath{\mathrm{bfs}(\ensuremath{\mathit{g}},\ensuremath{\mathit{r}})}$ algorithm.

Theorem 12..3   When given as input a Graph, $ \ensuremath{\ensuremath{\mathit{g}}}$, that is implemented using the AdjacencyLists data structure, the $ \ensuremath{\mathrm{bfs}(\ensuremath{\mathit{g}},\ensuremath{\mathit{r}})}$ algorithm runs in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{m}}}})$ time.

A breadth-first traversal has some very special properties. Calling $ \ensuremath{\mathrm{bfs}(\ensuremath{\mathit{g}},\ensuremath{\mathit{r}})}$ will eventually enqueue (and eventually dequeue) every vertex $ \ensuremath{\ensuremath{\mathit{j}}}$ such that there is a directed path from $ \ensuremath{\ensuremath{\mathit{r}}}$ to $ \ensuremath{\ensuremath{\mathit{j}}}$. Moreover, the vertices at distance 0 from $ \ensuremath{\ensuremath{\mathit{r}}}$ ( $ \ensuremath{\ensuremath{\mathit{r}}}$ itself) will enter $ \ensuremath{\ensuremath{\mathit{q}}}$ before the vertices at distance 1, which will enter $ \ensuremath{\ensuremath{\mathit{q}}}$ before the vertices at distance 2, and so on. Thus, the $ \ensuremath{\mathrm{bfs}(\ensuremath{\mathit{g}},\ensuremath{\mathit{r}})}$ method visits vertices in increasing order of distance from $ \ensuremath{\ensuremath{\mathit{r}}}$ and vertices that cannot be reached from $ \ensuremath{\ensuremath{\mathit{r}}}$ are never visited at all.

A particularly useful application of the breadth-first-search algorithm is, therefore, in computing shortest paths. To compute the shortest path from $ \ensuremath{\ensuremath{\mathit{r}}}$ to every other vertex, we use a variant of $ \ensuremath{\mathrm{bfs}(\ensuremath{\mathit{g}},\ensuremath{\mathit{r}})}$ that uses an auxilliary array, $ \ensuremath{\ensuremath{\mathit{p}}}$, of length $ \ensuremath{\ensuremath{\mathit{n}}}$. When a new vertex $ \ensuremath{\ensuremath{\mathit{j}}}$ is added to $ \ensuremath{\ensuremath{\mathit{q}}}$, we set $ \ensuremath{\ensuremath{\mathit{p}}[\ensuremath{j}]\gets \ensuremath{i}}$. In this way, $ \ensuremath{\ensuremath{\mathit{p}}[\ensuremath{\mathit{j}}]}$ becomes the second last node on a shortest path from $ \ensuremath{\ensuremath{\mathit{r}}}$ to $ \ensuremath{\ensuremath{\mathit{j}}}$. Repeating this, by taking $ \ensuremath{\ensuremath{\mathit{p}}[\ensuremath{\mathit{p}}[\ensuremath{\mathit{j}}]}$, $ \ensuremath{\ensuremath{\mathit{p}}[\ensuremath{\mathit{p}}[\ensuremath{\mathit{p}}[\ensuremath{\mathit{j}}]}]]$, and so on we can reconstruct the (reversal of) a shortest path from $ \ensuremath{\ensuremath{\mathit{r}}}$ to $ \ensuremath{\ensuremath{\mathit{j}}}$.

12.3.2 Depth-First Search

The depth-first-search algorithm is similar to the standard algorithm for traversing binary trees; it first fully explores one subtree before returning to the current node and then exploring the other subtree. Another way to think of depth-first-search is by saying that it is similar to breadth-first search except that it uses a stack instead of a queue.

During the execution of the depth-first-search algorithm, each vertex, $ \ensuremath{\ensuremath{\mathit{i}}}$, is assigned a colour, $ \ensuremath{\ensuremath{\mathit{c}}[\ensuremath{\mathit{i}}]}$: $ \ensuremath{\ensuremath{\mathit{white}}}$ if we have never seen the vertex before, $ \ensuremath{\ensuremath{\mathit{grey}}}$ if we are currently visiting that vertex, and $ \ensuremath{\ensuremath{\mathit{black}}}$ if we are done visiting that vertex. The easiest way to think of depth-first-search is as a recursive algorithm. It starts by visiting $ \ensuremath{\ensuremath{\mathit{r}}}$. When visiting a vertex $ \ensuremath{\ensuremath{\mathit{i}}}$, we first mark $ \ensuremath{\ensuremath{\mathit{i}}}$ as $ \ensuremath{\ensuremath{\mathit{grey}}}$. Next, we scan $ \ensuremath{\ensuremath{\mathit{i}}}$'s adjacency list and recursively visit any white vertex we find in this list. Finally, we are done processing $ \ensuremath{\ensuremath{\mathit{i}}}$, so we colour $ \ensuremath{\ensuremath{\mathit{i}}}$ black and return.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{dfs}(\ensure...
...it{c}}[\ensuremath{i}] \gets \ensuremath{black}}\\
\end{flushleft}\end{leftbar}
An example of the execution of this algorithm is shown in Figure 12.5.

Figure 12.5: An example of depth-first-search starting at node 0. Nodes are labelled with the order in which they are processed. Edges that result in a recursive call are drawn in black, other edges are drawn in $ \ensuremath{\ensuremath{\mathit{grey}}}$.
\includegraphics[scale=0.90909]{figs-python/graph-dfs}

Although depth-first-search may best be thought of as a recursive algorithm, recursion is not the best way to implement it. Indeed, the code given above will fail for many large graphs by causing a stack overflow. An alternative implementation is to replace the recursion stack with an explicit stack, $ \ensuremath{\ensuremath{\mathit{s}}}$. The following implementation does just that:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{dfs2}(\ensur...
...thit{s}}.\mathrm{push}(\ensuremath{\mathit{j}})}\\
\end{flushleft}\end{leftbar}
In the preceding code, when the next vertex, $ \ensuremath{\ensuremath{\mathit{i}}}$, is processed, $ \ensuremath{\ensuremath{\mathit{i}}}$ is coloured $ \ensuremath{\ensuremath{\mathit{grey}}}$ and then replaced, on the stack, with its adjacent vertices. During the next iteration, one of these vertices will be visited.

Not surprisingly, the running times of $ \ensuremath{\mathrm{dfs}(\ensuremath{\mathit{g}},\ensuremath{\mathit{r}})}$ and $ \ensuremath{\mathrm{dfs2}(\ensuremath{\mathit{g}},\ensuremath{\mathit{r}})}$ are the same as that of $ \ensuremath{\mathrm{bfs}(\ensuremath{\mathit{g}},\ensuremath{\mathit{r}})}$:

Theorem 12..4   When given as input a Graph, $ \ensuremath{\ensuremath{\mathit{g}}}$, that is implemented using the AdjacencyLists data structure, the $ \ensuremath{\mathrm{dfs}(\ensuremath{\mathit{g}},\ensuremath{\mathit{r}})}$ and $ \ensuremath{\mathrm{dfs2}(\ensuremath{\mathit{g}},\ensuremath{\mathit{r}})}$ algorithms each run in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{m}}}})$ time.

As with the breadth-first-search algorithm, there is an underlying tree associated with each execution of depth-first-search. When a node $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\neq \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}$ goes from $ \ensuremath{\ensuremath{\mathit{white}}}$ to $ \ensuremath{\ensuremath{\mathit{grey}}}$, this is because $ \ensuremath{\mathrm{dfs}(\ensuremath{\mathit{g}},\ensuremath{\mathit{i}},\ensuremath{\mathit{c}})}$ was called recursively while processing some node $ \ensuremath{i}'$. (In the case of $ \ensuremath{\mathrm{dfs2}(\ensuremath{\mathit{g}},\ensuremath{\mathit{r}})}$ algorithm, $ \ensuremath{\ensuremath{\mathit{i}}}$ is one of the nodes that replaced $ \ensuremath{i}'$ on the stack.) If we think of $ \ensuremath{i}'$ as the parent of $ \ensuremath{\ensuremath{\mathit{i}}}$, then we obtain a tree rooted at $ \ensuremath{\ensuremath{\mathit{r}}}$. In Figure 12.5, this tree is a path from vertex 0 to vertex 11.

An important property of the depth-first-search algorithm is the following: Suppose that when node $ \ensuremath{\ensuremath{\mathit{i}}}$ is coloured $ \ensuremath{\ensuremath{\mathit{grey}}}$, there exists a path from $ \ensuremath{\ensuremath{\mathit{i}}}$ to some other node $ \ensuremath{\ensuremath{\mathit{j}}}$ that uses only white vertices. Then $ \ensuremath{\ensuremath{\mathit{j}}}$ will be coloured first $ \ensuremath{\ensuremath{\mathit{grey}}}$ then $ \ensuremath{\ensuremath{\mathit{black}}}$ before $ \ensuremath{\ensuremath{\mathit{i}}}$ is coloured $ \ensuremath{\ensuremath{\mathit{black}}}$. (This can be proven by contradiction, by considering any path $ P$ from $ \ensuremath{\ensuremath{\mathit{i}}}$ to $ \ensuremath{\ensuremath{\mathit{j}}}$.)

One application of this property is the detection of cycles. Refer to Figure 12.6. Consider some cycle, $ C$, that can be reached from $ \ensuremath{\ensuremath{\mathit{r}}}$. Let $ \ensuremath{\ensuremath{\mathit{i}}}$ be the first node of $ C$ that is coloured $ \ensuremath{\ensuremath{\mathit{grey}}}$, and let $ \ensuremath{\ensuremath{\mathit{j}}}$ be the node that precedes $ \ensuremath{\ensuremath{\mathit{i}}}$ on the cycle $ C$. Then, by the above property, $ \ensuremath{\ensuremath{\mathit{j}}}$ will be coloured $ \ensuremath{\ensuremath{\mathit{grey}}}$ and the edge $ \ensuremath{(\ensuremath{\mathit{j}},\ensuremath{\mathit{i}})}$ will be considered by the algorithm while $ \ensuremath{\ensuremath{\mathit{i}}}$ is still $ \ensuremath{\ensuremath{\mathit{grey}}}$. Thus, the algorithm can conclude that there is a path, $ P$, from $ \ensuremath{\ensuremath{\mathit{i}}}$ to $ \ensuremath{\ensuremath{\mathit{j}}}$ in the depth-first-search tree and the edge $ \ensuremath{(\ensuremath{\mathit{j}},\ensuremath{\mathit{i}})}$ exists. Therefore, $ P$ is also a cycle.

Figure 12.6: The depth-first-search algorithm can be used to detect cycles in $ G$. The node $ \ensuremath{\ensuremath{\mathit{j}}}$ is coloured $ \ensuremath{\ensuremath{\mathit{grey}}}$ while $ \ensuremath{\ensuremath{\mathit{i}}}$ is still $ \ensuremath{\ensuremath{\mathit{grey}}}$. This implies that there is a path, $ P$, from $ \ensuremath{\ensuremath{\mathit{i}}}$ to $ \ensuremath{\ensuremath{\mathit{j}}}$ in the depth-first-search tree, and the edge $ \ensuremath{(\ensuremath{\mathit{j}},\ensuremath{\mathit{i}})}$ implies that $ P$ is also a cycle.
\includegraphics[scale=0.90909]{figs-python/dfs-cycle}

opendatastructures.org

Basic HTML syntax

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.

Basic HTML syntax

In this article, we cover the fundamentals of HTML, including terminology, syntax, and structure. Along the way, you'll complete some interactive challenges to become familiar with writing basic HTML.

Prerequisites: Basic software installed, and basic knowledge of working with files.
Learning outcomes:
  • The anatomy of an HTML element — element, opening tag, content, closing tag, attributes.
  • The HTML body and its purpose as a container for the page content.
  • What void elements are, and how they differ from other elements.
  • The need for a doctype at the top of HTML documents, including its original intended purpose, and the fact that it is now somewhat of a historical artifact.
  • Understanding that HTML needs to be correctly nested.

What is HTML?

HTML (HyperText Markup Language) is a markup language that tells web browsers how to structure the web pages you visit. HTML consists of a series of elements, which you use to enclose, wrap, or mark up different parts of content to make it appear or act in a certain way. The enclosing tags can make content into a hyperlink to link to another page, italicize words, and so on. For example, consider the following line of text:

My cat is very grumpy

We could specify that this text is a paragraph by enclosing it in paragraph (<p>) tags:

html
<p>My cat is very grumpy</p>

Or, we could specify that this text is a top-level heading by enclosing it in <h1> tags:

html
<h1>My cat is very grumpy</h1>

HTML lives inside text files called HTML documents, or just documents, with a .html file extension. Where previously we've talked about web pages, an HTML document contains the web page's content and specifies its structure.

The most common HTML file you'll encounter is index.html, which is generally used to contain a website's home page content. It's also common to see subfolders containing their own index.html files, so a website can have multiple index files in different places.

Note: Tags in HTML are not case-sensitive. This means they can be written in uppercase or lowercase. For example, a <title> tag could be written as <title>, <TITLE>, <Title>, <TiTlE>, etc., and it will work. However, it is best practice to write all tags in lowercase for consistency and readability.

Anatomy of an HTML element

Let's further explore our paragraph element from the previous section:

A sample code snippet demonstrating the structure of an html element.<p> My cat is very grumpy </p>.

Our complete element consists of:

  • The opening tag: This consists of the name of the element (in this example, p for paragraph), wrapped in opening and closing angle brackets. This opening tag marks where the element begins or starts to take effect. In this example, it precedes the start of the paragraph text.
  • The content: This is the content of the element. In this example, it is the paragraph text — "My cat is very grumpy".
  • The closing tag: This is the same as the opening tag, except that it includes a forward slash before the element name. This marks where the element ends. Failing to include a closing tag is a common beginner error that can produce peculiar results.

Note: Head on over to our learning partner Scrimba's HTML tags MDN learning partner scrim for an interactive explanation of HTML tags.

Creating your first HTML element

Let's give you some practice at writing your own HTML elements:

  1. Click "Play" in the code block below to edit the example in the MDN Playground.
  2. Wrap the line of text with the tags <em> and </em>. To open the element, put the opening tag (<em>) at the start of the line. To close the element, put the closing tag (</em>) at the end of the line. Doing this should format the rendered text as italic text.
  3. If you are feeling adventurous, try researching some more HTML elements and applying them to the text example.

If you make a mistake, you can clear your work using the Reset button in the MDN Playground. If you get really stuck, you can view the solution below the code block.

html
This is my text.
Click here to show the solution

Your finished line of HTML should look like this:

html
<em>This is my text.</em>

Nesting elements

Elements can be placed within other elements. This is called nesting. If we wanted to state that our cat is very grumpy, we could wrap the word very in a <strong> element, which gives the word strong(er) text formatting:

html
<p>My cat is <strong>very</strong> grumpy.</p>

In this code block, the text "My cat is very grumpy." is all defined as a paragraph. The word "very" is additionally defined as having strong importance.

There is a right and wrong way to do nesting. In the code block above, we open the <p> element first, then open the <strong> element. For proper nesting, we close the <strong> element first, then close the <p>.

The following is an example of the wrong way to do nesting:

html
<p>My cat is <strong>very grumpy.</p></strong>

The tags have to open and close so that they are inside or outside one another. Because the elements overlap in the previous code block, the browser has to guess at your intent. This kind of guessing can result in unexpected results.

Void elements

Not all elements follow the pattern of an opening tag, content, then a closing tag. Some elements consist of a single tag, which is typically used to insert/embed something in the document. Such elements are called void elements, which means "elements that cannot contain other HTML content".

For example, the <br> element inserts a line break into a line of text, which causes it to break onto multiple lines:

html
<p>
  This is a single paragraph, but we are going to <br />break it onto two lines.
</p>

This renders as follows:

Note: In some HTML examples, you'll see a / added at the end of a void element's tag, for example <br />. This is a different style of markup syntax, which isn't wrong, but this "closing slash" is not needed.

Attributes

Elements can also have attributes. Attributes look like this:

paragraph tag with 'class="editor-note"' attribute emphasized

Attributes contain extra information about the element that isn't part of its content. The class attribute provides an identifying name that can be used to target the element with styles (CSS) or scripting information (JavaScript).

An attribute should have:

  • A space between it and the element name. When an element has more than one attribute, the attributes should be separated by spaces too.
  • The attribute name, followed by an equals sign (=).
  • An attribute value, wrapped with opening and closing quote marks.

Adding attributes to an element

Now it's your turn again. In this section you are going to explore the <img> element, which is used to display an image on the page. The <img> element can take several attributes, including:

  • src: A required attribute that specifies the URL (web address) of the image. For example: src="https://mdn.github.io/shared-assets/images/examples/fx-nightly-512.png".
  • alt: Specifies a text description to describe the image to people who cannot see it. For example: alt="The Firefox Nightly icon". This attribute is not technically required, but you really should provide a text description for all images that convey meaning (as opposed to being purely decorative).
  • width: Specifies the width of the image in pixels. For example: width="300".
  • height: Specifies the height of the image in pixels. For example: height="300".

Follow the steps below to complete the task:

  1. Click "Play" in the code block below to edit the example in the MDN Playground.
  2. Find your favorite image online, right click it, and press Copy Image Link/Address. Alternatively, copy the image URL above.
  3. Back in the MDN Playground, add the src attribute to the <img> element and set its value to the URL from Step 2.
  4. Set the alt attribute to a suitable description of the image.
  5. Set the width attribute to a value of say 300 so you can see the image a bit better inside the output panel. Adjust the value if needed.

If you make a mistake, you can clear your work using the Reset button in the MDN Playground. If you get really stuck, you can view the solution below the code block.

html
<img />
Click here to show the solution

Your finished HTML element should look something like this:

html
<img
  src="https://mdn.github.io/shared-assets/images/examples/fx-nightly-512.png"
  alt="A description of the image"
  width="300" />

Boolean attributes

Sometimes you will see HTML attributes written without values. These are called Boolean attributes. When a boolean attribute is added, its value is set to true, irrespective of whatever value is assigned to it (even no value). If an attribute is not included in an HTML tag, its value is set to false.

For example, consider the disabled attribute, which you can assign to form <input> elements to stop the user entering data into them. For example:

html
<label for="first-input">This input is disabled</label>
<input id="first-input" type="text" disabled="disabled" />
<br />

As shorthand, it is acceptable to write the disabled attribute without a value:

html
<label for="second-input">This input is also disabled</label>
<input id="second-input" type="text" disabled />
<br />

For reference, let's also provide a non-disabled <input> element so you can compare and contrast (note how the disabled inputs are somewhat grayed out in the below rendering):

html
<label for="third-input">This input isn't disabled; you can type into it</label>
<input id="third-input" type="text" />

The above HTML snippets render like so:

Note: The <label> elements included in the above code provide a way to associate descriptive labels with form elements. We included them because it is a best practice, and to provide some separation between the form inputs.

Omitting quotes around attribute values

It is OK to omit the quotes from around attribute values in certain circumstances. But because this can break your markup in other circumstances, we advise you to always include the quote marks. Let's explore why.

The element in the code snippet below, <a>, is called an anchor. Anchors enclose text and turn them into links. The href attribute specifies the URL the link points to. You can omit the quotes around the href attribute value shown below without any negative consequences, because it has no spaces in it:

html
<a href=https://www.mozilla.org/>favorite website</a>

However, you soon run into problems when omitting quotes from attribute values with spaces. Consider the title attribute shown below, which provides a description of the linked page ("The Mozilla homepage") that should appear as a tooltip when the link is hovered over by a mouse pointer.

html
<a href=https://www.mozilla.org/ title=The Mozilla homepage>favorite website</a>

Because quotes are not included around the title attribute value, the browser interprets it as three attributes: a title attribute with the value The, and two Boolean attributes — Mozilla and homepage. Obviously, this is not what we intended! If you're using a device with a mouse pointer, you can try hovering over the link to view the title tooltip (it will give you "The" rather than the intended "The Mozilla homepage").

Always include quotes around attribute values. It avoids errors and unintended behavior, and results in more readable code.

Single or double quotes?

In this article, we have wrapped all our attribute values in double quotes. However, you might see single quotes used in some HTML code. This is a matter of style. You can feel free to choose which one you prefer. Both of these lines are equivalent:

html
<a href='https://www.example.com'>A link to my example.</a>

<a href="https://www.example.com">A link to my example.</a>

Make sure you don't mix single quotes and double quotes. The below example mixes quotes, which will lead to errors because as far as the browser is concerned, the href attribute value has not been finished:

html
<a href="https://www.example.com'>A link to my example.</a>

If you use one type of quote, you can include the other type of quote inside your attribute values. This works fine:

html
<a href="https://www.example.com" title="Isn't this fun?">
  A link to my example.
</a>

To use quote marks inside other quote marks of the same type (single quote or double quote), you can use character references. For example, this will break:

html
<a href="https://www.example.com" title="An "interesting" reference">A link to my example.</a>

Instead, you need to do this:

html
<a href="https://www.example.com" title="An &quot;interesting&quot; reference">A link to my example.</a>

Anatomy of an HTML document

Individual HTML elements aren't very useful on their own. Next, let's examine how individual elements combine to form an entire HTML page.

The following example is a very simple complete webpage:

html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>My test page</title>
  </head>
  <body>
    <p>This is my page</p>
  </body>
</html>

The parts of this example are as follows:

  1. <!doctype html>: The doctype. When HTML was young (1991-1992), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML. Doctypes used to look something like this:

    html
    <!doctype html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    

    In modern times, the doctype is a historical artifact that needs to be included for everything else to work correctly. <!doctype html> is the shortest string of characters that counts as a valid doctype, and it should be included at the top of all webpages. That is all you need to know!

  2. <html></html>: The <html> element. This element wraps all the content on the page. It is sometimes known as the root element.

  3. <head></head>: The <head> element. This element acts as a container for information about the page that isn't part of the content that users will see. This can include keywords and a page description to be shown in search results, CSS to style content, character set declarations, and more. You will learn more about the head of the page in the next article.

  4. <meta charset="utf-8">: A <meta> element. This element represents metadata that describes the page. The charset attribute specifies the character encoding your document will use. UTF-8 includes most characters from the vast majority of human written languages, which means the page will be able to display different languages successfully. There is no reason not to set this, and it can help avoid some problems later.

  5. <title></title>: The <title> element. This sets the title of the page, which is the title that appears in the browser tab the page is loaded in. The page title is also used to describe the page when it is bookmarked.

  6. <body></body>: The <body> element. This contains all the content that displays on the page, including text, images, videos, games, playable audio tracks, and so on.

Adding some features to an HTML document

At this point, we want you to practice writing some slightly more substantial HTML content. To do this, you've got a couple of options — you can create the HTML on your local computer, or use the MDN Playground like in the previous examples.

Example setup

  • To do it on your local machine:
    1. Copy the HTML page example listed in the previous section and paste it into a new file in your code editor. You can also find this basic HTML template on our GitHub repo.
    2. Make the changes to the page outlined in the instructions.
    3. Save the file as index.html then load it in a new browser tab to see the results.
  • To do it in the MDN Playground, click "Play" in the output panel below to edit the example, then follow the instructions. If you make a mistake, you can clear your work using the Reset button in the MDN Playground.

Example instructions

Here are the instructions to follow:

  1. Just below the opening tag of the <body> element, add a main title for the document. This should be wrapped by <h1></h1> opening and closing tags.
  2. Edit the paragraph content to include text about a topic that you find interesting.
  3. Make important words stand out in bold by wrapping them inside a <strong> element.
  4. Add two links to your paragraph. This is achieved using the <a> element.
  5. Add an image to your document below the paragraph as explained earlier. If it is too big to see, add a width attribute to shrink it down.

If you get really stuck, you can view a potential solution here:

Click here to show the solution

The contents of your finished HTML element body should look something like this:

html
<h1>Some music</h1>
<p>
  I really enjoy <strong>playing the drums</strong>. One of my favorite drummers
  is Neal Peart, who used to play in the band
  <a href="https://en.wikipedia.org/wiki/Rush_%28band%29">Rush</a>. My favorite
  Rush album is currently
  <a href="https://www.deezer.com/album/942295">Moving Pictures</a>.
</p>
<img
  src="https://www.cygnus-x1.net/links/rush/images/albums/sectors/sector2-movingpictures-cover-s.jpg"
  alt="Rush Moving Pictures album cover"
  width="300" />

Whitespace in HTML

In previous examples, we've included lot of whitespace in the code. In most cases this is completely optional, and included mainly to make the code more readable. For example, these two code snippets are equivalent:

html
<p id="noWhitespace">Dogs are silly.</p>

<p id="whitespace">Dogs
    are
        silly.</p>

They both render exactly the same:

In almost all elements (there are exceptions such as <pre>), no matter how much whitespace you use inside HTML element content, the HTML parser reduces each sequence of whitespace to a single space when rendering the code.

It is up to you to choose a preferred code formatting style. It is common to give each nested element two spaces of indentation more than the one it is sitting inside; this is the style we use on MDN.

For example:

html
<section>
  <div>
    <p>A paragraph of content.</p>
  </div>
</section>

Character references: including special characters in HTML

In HTML, the characters <, >, ", ', and & are special characters. They are parts of the HTML syntax itself. So how do you include these special characters in your text? For example, how can you use a literal ampersand or less-than sign in your content without it being interpreted as code?

You do this with character references. These are special codes that represent characters, to be used in these exact circumstances. Each character reference starts with an ampersand (&), and ends with a semicolon (;).

Literal character Character reference equivalent
< &lt;
> &gt;
" &quot;
' &apos;
& &amp;

Character references are fairly easily remembered because the text they use is an abbreviation of the character name — for example "lt" = "less than", "quot" = "quotation", and "amp" = "ampersand". To learn more about entity references, see List of XML and HTML character entity references (Wikipedia).

In the example below, there are two paragraphs:

html
<p>In HTML, you define a paragraph using the <p> element.</p>

<p>In HTML, you define a paragraph using the &lt;p&gt; element.</p>

This renders as follows:

You can see that the first paragraph has gone wrong, because the browser has interpreted the second instance of <p> as starting a new paragraph. The second paragraph renders fine because the angle brackets of the content "<p>" are represented by character references.

Note: You don't need to use entity references for any other symbols, as modern browsers will handle the actual symbols just fine as long as your HTML's character encoding is set to UTF-8.

HTML comments

HTML has a mechanism to write comments in the code. Browsers ignore comments, therefore they are invisible to the user. The purpose of comments is to allow you to include notes in the code to explain how it works. This is very useful if you return to a code base after being away for long enough that you don't remember it, or if someone else starts working on it that has never seen it before.

To write an HTML comment, wrap it in the special markers <!-- and -->, as shown below:

html
<p>I'm not inside a comment</p>

<!-- <p>I am!</p> -->

This code renders as follows:

Only the first paragraph is displayed in the live output; the second line is not rendered because it is an HTML comment.

Summary

You made it to the end of the article! We hope you enjoyed your tour of the basics of HTML.

At this point, you should understand what HTML looks like, and how it works at a basic level. You should also be able to write a few elements and attributes. The subsequent articles of this module go further on some of the topics introduced here, as well as presenting additional topics.

Note: As you start to learn more about HTML, consider also learning the basics of CSS, the language used to style web pages (for example, changing colors, fonts, and spacing). HTML and CSS are used together on most web pages, and learning them at the same time can be effective.

DOM scripting introduction

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.

DOM scripting introduction

When writing web pages and apps, one of the most common things you'll want to do is change the document structure in some way. This is usually done by manipulating the Document Object Model (DOM) via a set of built-in browser APIs for controlling HTML and styling information. In this article we'll introduce you to DOM scripting.

Prerequisites: An understanding of HTML and the fundamentals of CSS, familiarity with JavaScript basics as covered in previous lessons.
Learning outcomes:
  • What the DOM is — the browser's internal representation of the document's HTML structure as a hierarchy of objects.
  • The important parts of a web browser as represented in JavaScript — Navigator, Window, and Document.
  • How DOM nodes exist relative to each other in the DOM tree — root, parent, child, sibling, and descendant.
  • Getting references to DOM nodes, creating new nodes, adding and removing nodes and attributes.
  • Manipulating CSS styles with JavaScript.

The important parts of a web browser

Web browsers are very complicated pieces of software with a lot of moving parts, many of which can't be controlled or manipulated by a web developer using JavaScript. You might think that such limitations are a bad thing, but browsers are locked down for good reasons, mostly centering around security. Imagine if a website could get access to your stored passwords or other sensitive information, and log into websites as if it were you?

Despite the limitations, Web APIs still give us access to a lot of functionality that enable us to do a great many things with web pages. There are a few really obvious bits you'll reference regularly in your code — consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages:

Important parts of web browser; the document is the web page. The window includes the entire document and also the tab. The navigator is the browser, which includes the window (which includes the document) and all other windows.

  • The window represents the browser tab that a web page is loaded into; this is represented in JavaScript by the Window object. Using methods available on this object you can do things like return the window's size (see Window.innerWidth and Window.innerHeight), manipulate the document loaded into that window, store data specific to that document on the client-side (for example using a local database or other storage mechanism), attach an event handler to the current window, and more.
  • The navigator represents the state and identity of the browser as it exists on the web. In JavaScript, this is represented by the Navigator object. You can use this object to retrieve things like the user's preferred language, a media stream from the user's webcam, etc.
  • The document (represented by the DOM in browsers) is the actual page loaded into the window, and is represented in JavaScript by the Document object. You can use this object to return and manipulate information on the HTML and CSS that comprises the document, for example get a reference to an element in the DOM, change its text content, apply new styles to it, create new elements and add them to the current element as children, or even delete it altogether.

In this article we'll focus mostly on manipulating the document, but we'll show a few other useful bits besides.

The document object model

Let's provide a brief recap on the Document Object Model (DOM), which we also looked at earlier in the course. The document currently loaded in each one of your browser tabs is represented by a DOM. This is a "tree structure" representation created by the browser that enables the HTML structure to be easily accessed by programming languages — for example the browser itself uses it to apply styling and other information to the correct elements as it renders a page, and developers like you can manipulate the DOM with JavaScript after the page has been rendered.

Note: Scrimba's The Document Object Model MDN learning partner provides a handy walkthrough of the "DOM" term and what it means.

We have created an example page at dom-example.html (see it live also). Try opening this up in your browser — it is a very simple page containing a <section> element inside which you can find an image, and a paragraph with a link inside. The HTML source code looks like this:

html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>Simple DOM example</title>
  </head>
  <body>
    <section>
      <img
        src="dinosaur.png"
        alt="A red Tyrannosaurus Rex: A two legged dinosaur
        standing upright like a human, with small arms, and a
        large head with lots of sharp teeth." />
      <p>
        Here we will add a link to the
        <a href="https://www.mozilla.org/">Mozilla homepage</a>
      </p>
    </section>
  </body>
</html>

The DOM on the other hand looks like this:

Tree structure representation of Document Object Model: The top node is the doctype and HTML element. Child nodes of the HTML include head and body. Each child element is a branch. All text, even white space, is shown as well.

Note: This DOM tree diagram was created using Ian Hickson's Live DOM viewer.

Each entry in the tree is called a node. You can see in the diagram above that some nodes represent elements (identified as HTML, HEAD, META and so on) and others represent text (identified as #text). There are other types of nodes as well, but these are the main ones you'll encounter.

Nodes are also referred to by their position in the tree relative to other nodes:

  • Root node: The top node in the tree, which in the case of HTML is always the HTML node (other markup vocabularies like SVG and custom XML will have different root elements).
  • Child node: A node directly inside another node. For example, IMG is a child of SECTION in the above example.
  • Descendant node: A node anywhere inside another node. For example, IMG is a child of SECTION in the above example, and it is also a descendant. IMG is not a child of BODY, as it is two levels below it in the tree, but it is a descendant of BODY.
  • Parent node: A node which has another node inside it. For example, BODY is the parent node of SECTION in the above example.
  • Sibling nodes: Nodes that sit on the same level under the same parent node in the DOM tree. For example, IMG and P are siblings in the above example.

It is useful to familiarize yourself with this terminology before working with the DOM, as a number of the code terms you'll come across make use of them. You'll also come across them in CSS (for example, descendant selector, child selector).

Doing some basic DOM manipulation

To start learning about DOM manipulation, let's begin with a practical example.

  1. Take a local copy of the dom-example.html page and the image that goes along with it.

  2. Add a <script></script> element just above the closing </body> tag.

  3. To manipulate an element inside the DOM, you first need to select it and store a reference to it inside a variable. Inside your script element, add the following line:

    js
    const link = document.querySelector("a");
    
  4. Now we have the element reference stored in a variable, we can start to manipulate it using properties and methods available to it (these are defined on interfaces like HTMLAnchorElement in the case of <a> element, its more general parent interface HTMLElement, and Node — which represents all nodes in a DOM). First of all, let's change the text inside the link by updating the value of the Node.textContent property. Add the following line below the previous one:

    js
    link.textContent = "Mozilla Developer Network";
    
  5. We should also change the URL the link is pointing to, so that it doesn't go to the wrong place when it is clicked on. Add the following line, again at the bottom:

    js
    link.href = "https://developer.mozilla.org";
    

Note that, as with many things in JavaScript, there are many ways to select an element and store a reference to it in a variable. Document.querySelector() is the recommended modern approach. It is convenient because it allows you to select elements using CSS selectors. The above querySelector() call will match the first <a> element that appears in the document. If you wanted to match and do things to multiple elements, you could use Document.querySelectorAll(), which matches every element in the document that matches the selector, and stores references to them in an array-like object called a NodeList.

There are older methods available for grabbing element references, such as:

  • Document.getElementById(), which selects an element with a given id attribute value, e.g., <p id="myId">My paragraph</p>. The ID is passed to the function as a parameter, i.e., const elementRef = document.getElementById('myId').
  • Document.getElementsByTagName(), which returns an array-like object containing all the elements on the page of a given type, for example <p>s, <a>s, etc. The element type is passed to the function as a parameter, i.e., const elementRefArray = document.getElementsByTagName('p').

These two work better in older browsers than the modern methods like querySelector(), but are not as convenient. Have a look and see what others you can find!

Creating and placing new nodes

The above has given you a little taste of what you can do, but let's go further and look at how we can create new elements.

  1. Going back to the current example, let's start by grabbing a reference to our <section> element — add the following code at the bottom of your existing script (do the same with the other lines too):

    js
    const sect = document.querySelector("section");
    
  2. Now let's create a new paragraph using Document.createElement() and give it some text content in the same way as before:

    js
    const para = document.createElement("p");
    para.textContent = "We hope you enjoyed the ride.";
    
  3. You can now append the new paragraph at the end of the section using Node.appendChild():

    js
    sect.appendChild(para);
    
  4. Finally for this part, let's add a text node to the paragraph the link sits inside, to round off the sentence nicely. First we will create the text node using Document.createTextNode():

    js
    const text = document.createTextNode(
      " — the premier source for web development knowledge.",
    );
    
  5. Now we'll grab a reference to the paragraph the link is inside, and append the text node to it:

    js
    const linkPara = document.querySelector("p");
    linkPara.appendChild(text);
    

That's most of what you need for adding nodes to the DOM — you'll make a lot of use of these methods when building dynamic interfaces (we'll look at some examples later).

Moving and removing elements

There may be times when you want to move nodes, or delete them from the DOM altogether. This is perfectly possible.

If we wanted to move the paragraph with the link inside it to the bottom of the section, we could do this:

js
sect.appendChild(linkPara);

This moves the paragraph down to the bottom of the section. You might have thought it would make a second copy of it, but this is not the case — linkPara is a reference to the one and only copy of that paragraph. If you wanted to make a copy and add that as well, you'd need to use Node.cloneNode() instead.

Removing a node is pretty simple as well, at least when you have a reference to the node to be removed and its parent. In our current case, we just use Node.removeChild(), like this:

js
sect.removeChild(linkPara);

When you want to remove a node based only on a reference to itself, which is fairly common, you can use Element.remove():

js
linkPara.remove();

This method is not supported in older browsers. They have no method to tell a node to remove itself, so you'd have to do the following:

js
linkPara.parentNode.removeChild(linkPara);

Have a go at adding the above lines to your code.

Manipulating styles

It is possible to manipulate CSS styles via JavaScript in a variety of ways.

To start with, you can get a list of all the stylesheets attached to a document using Document.styleSheets, which returns an array-like object with CSSStyleSheet objects. You can then add/remove styles as wished. However, we're not going to expand on those features because they are a somewhat archaic and difficult way to manipulate style. There are much easier ways.

The first way is to add inline styles directly onto elements you want to dynamically style. This is done with the HTMLElement.style property, which contains inline styling information for each element in the document. You can set properties of this object to directly update element styles.

  1. As an example, try adding these lines to our ongoing example:

    js
    para.style.color = "white";
    para.style.backgroundColor = "black";
    para.style.padding = "10px";
    para.style.width = "250px";
    para.style.textAlign = "center";
    
  2. Reload the page and you'll see that the styles have been applied to the paragraph. If you look at that paragraph in your browser's Page Inspector/DOM inspector, you'll see that these lines are indeed adding inline styles to the document:

    html
    <p
      style="color: white; background-color: black; padding: 10px; width: 250px; text-align: center;">
      We hope you enjoyed the ride.
    </p>
    

Note: Notice how the JavaScript property versions of the CSS styles are written in lower camel case whereas the CSS versions are hyphenated (kebab-case) (e.g., backgroundColor versus background-color). Make sure you don't get these mixed up, otherwise it won't work.

There is another common way to dynamically manipulate styles on your document, which is to write the styles in a separate stylesheet, and reference those styles by adding/removing a class name.

  1. Delete the previous five lines you added to the JavaScript.

  2. Add the following inside your HTML <head>:

    html
    <style>
      .highlight {
        color: white;
        background-color: black;
        padding: 10px;
        width: 250px;
        text-align: center;
      }
    </style>
    
  3. To add this class name to your element, use the element's classList's add() method:

    js
    para.classList.add("highlight");
    
  4. Refresh your page, and you'll see no change — the CSS is still applied to the paragraph, but this time by giving it a class that is selected by our CSS rule, not as inline CSS styles.

Which method you choose is up to you; both have their advantages and disadvantages. The first method takes less setup and is good for simple uses, whereas the second method is more purist (no mixing CSS and JavaScript, no inline styles, which are seen as a bad practice). As you start building larger and more involved apps, you will probably start using the second method more, but it is really up to you.

At this point, we haven't really done anything useful! There is no point using JavaScript to create static content — you might as well just write it into your HTML and not use JavaScript. It is more complex than HTML, and creating your content with JavaScript also has other issues attached to it (such as not being readable by search engines).

In the next section we will look at a more practical use of DOM APIs.

Note: You can find our finished version of the dom-example.html demo on GitHub (see it live also).

Creating a dynamic shopping list

In this exercise, we want you to build a dynamic shopping list that allows you to add items using a form input and a button. After you type an item in the input field and click the button or press the Enter key, the following should happen:

  • The item should appear in the list.
  • Each item should have a button next to it that removes the item from the list when clicked.
  • The input fields should be cleared and focused, ready for the next item entry.

The finished demo will look something like the following — try it out before you build it!

To complete the exercise, follow the steps below, and make sure that the list behaves as described above.

  1. To begin, download a copy of our shopping-list.html starting file and make a copy of it somewhere. You'll see that it has some minimal CSS, a form with a label, input, and button, an empty list, and a <script> element. You'll be making all your additions inside the script.
  2. Create three variables that hold references to the list (<ul>), <input>, and <button> elements.
  3. Create a function that will run in response to the button being clicked.
  4. Inside the function body, start by calling preventDefault(). Since the input is wrapped in a form element, pressing the Enter key will trigger the form to submit. The call to preventDefault() will prevent the form from refreshing the page so a new item can be added to the list instead.
  5. Continue by storing the current value of the input in a variable.
  6. Next, clear the input element by setting its value to an empty string ("").
  7. Create three new elements — a list item (<li>), a <span>, and a <button> — and store them in variables.
  8. Append the span and button as children of the list item.
  9. Set the text content of the span to the input value you saved earlier, and set the text content of the button to Delete.
  10. Append the list item to the list.
  11. Attach an event handler to the Delete button so that, when clicked, it removes the entire list item (<li>...</li>).
  12. Finally, use the focus() method to focus the input element, so it's ready for entering the next shopping list item.

Summary

We have reached the end of our study of document and DOM manipulation. At this point you should understand what the important parts of a web browser are with respect to controlling documents and other aspects of the user's web experience. Most importantly, you should understand what the Document Object Model is, and how to manipulate it to create useful functionality.

See also

3.2. Views #

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

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

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

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

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

3.2. Views #

Refer back to the queries in Section 2.6. Suppose the combined listing of weather records and city location is of particular interest to your application, but you do not want to type the query each time you need it. You can create a view over the query, which gives a name to the query that you can refer to like an ordinary table:

CREATE VIEW myview AS
    SELECT name, temp_lo, temp_hi, prcp, date, location
        FROM weather, cities
        WHERE city = name;

SELECT * FROM myview;

Making liberal use of views is a key aspect of good SQL database design. Views allow you to encapsulate the details of the structure of your tables, which might change as your application evolves, behind consistent interfaces.

Views can be used in almost any place a real table can be used. Building views upon other views is not uncommon.

22.1. Geometry and Linear Algebraic Operations 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.1. Geometry and Linear Algebraic Operations
Open the notebook in SageMaker Studio Lab

In Section 2.3, we encountered the basics of linear algebra and saw how it could be used to express common operations for transforming our data. Linear algebra is one of the key mathematical pillars underlying much of the work that we do in deep learning and in machine learning more broadly. While Section 2.3 contained enough machinery to communicate the mechanics of modern deep learning models, there is a lot more to the subject. In this section, we will go deeper, highlighting some geometric interpretations of linear algebra operations, and introducing a few fundamental concepts, including of eigenvalues and eigenvectors.

22.1.1. Geometry of Vectors

First, we need to discuss the two common geometric interpretations of vectors, as either points or directions in space. Fundamentally, a vector is a list of numbers such as the Python list below.

v = [1, 7, 0, 1]

Mathematicians most often write this as either a column or row vector, which is to say either as

(22.1.1)\[\begin{split}\mathbf{x} = \begin{bmatrix}1\\7\\0\\1\end{bmatrix},\end{split}\]

or

(22.1.2)\[\mathbf{x}^\top = \begin{bmatrix}1 & 7 & 0 & 1\end{bmatrix}.\]

These often have different interpretations, where data examples are column vectors and weights used to form weighted sums are row vectors. However, it can be beneficial to be flexible. As we have described in Section 2.3, though a single vector’s default orientation is a column vector, for any matrix representing a tabular dataset, treating each data example as a row vector in the matrix is more conventional.

Given a vector, the first interpretation that we should give it is as a point in space. In two or three dimensions, we can visualize these points by using the components of the vectors to define the location of the points in space compared to a fixed reference called the origin. This can be seen in Fig. 22.1.1.

../_images/grid-points.svg

Fig. 22.1.1 An illustration of visualizing vectors as points in the plane. The first component of the vector gives the \(\mathit{x}\)-coordinate, the second component gives the \(\mathit{y}\)-coordinate. Higher dimensions are analogous, although much harder to visualize.

This geometric point of view allows us to consider the problem on a more abstract level. No longer faced with some insurmountable seeming problem like classifying pictures as either cats or dogs, we can start considering tasks abstractly as collections of points in space and picturing the task as discovering how to separate two distinct clusters of points.

In parallel, there is a second point of view that people often take of vectors: as directions in space. Not only can we think of the vector \(\mathbf{v} = [3,2]^\top\) as the location \(3\) units to the right and \(2\) units up from the origin, we can also think of it as the direction itself to take \(3\) steps to the right and \(2\) steps up. In this way, we consider all the vectors in figure Fig. 22.1.2 the same.

../_images/par-vec.svg

Fig. 22.1.2 Any vector can be visualized as an arrow in the plane. In this case, every vector drawn is a representation of the vector \((3,2)^\top\).

One of the benefits of this shift is that we can make visual sense of the act of vector addition. In particular, we follow the directions given by one vector, and then follow the directions given by the other, as is seen in Fig. 22.1.3.

../_images/vec-add.svg

Fig. 22.1.3 We can visualize vector addition by first following one vector, and then another.

Vector subtraction has a similar interpretation. By considering the identity that \(\mathbf{u} = \mathbf{v} + (\mathbf{u}-\mathbf{v})\), we see that the vector \(\mathbf{u}-\mathbf{v}\) is the direction that takes us from the point \(\mathbf{v}\) to the point \(\mathbf{u}\).

22.1.2. Dot Products and Angles

As we saw in Section 2.3, if we take two column vectors \(\mathbf{u}\) and \(\mathbf{v}\), we can form their dot product by computing:

(22.1.3)\[\mathbf{u}^\top\mathbf{v} = \sum_i u_i\cdot v_i.\]

Because (22.1.3) is symmetric, we will mirror the notation of classical multiplication and write

(22.1.4)\[\mathbf{u}\cdot\mathbf{v} = \mathbf{u}^\top\mathbf{v} = \mathbf{v}^\top\mathbf{u},\]

to highlight the fact that exchanging the order of the vectors will yield the same answer.

The dot product (22.1.3) also admits a geometric interpretation: it is closely related to the angle between two vectors. Consider the angle shown in Fig. 22.1.4.

../_images/vec-angle.svg

Fig. 22.1.4 Between any two vectors in the plane there is a well defined angle \(\theta\). We will see this angle is intimately tied to the dot product.

To start, let’s consider two specific vectors:

(22.1.5)\[\mathbf{v} = (r,0) \; \textrm{and} \; \mathbf{w} = (s\cos(\theta), s \sin(\theta)).\]

The vector \(\mathbf{v}\) is length \(r\) and runs parallel to the \(x\)-axis, and the vector \(\mathbf{w}\) is of length \(s\) and at angle \(\theta\) with the \(x\)-axis. If we compute the dot product of these two vectors, we see that

(22.1.6)\[\mathbf{v}\cdot\mathbf{w} = rs\cos(\theta) = \|\mathbf{v}\|\|\mathbf{w}\|\cos(\theta).\]

With some simple algebraic manipulation, we can rearrange terms to obtain

(22.1.7)\[\theta = \arccos\left(\frac{\mathbf{v}\cdot\mathbf{w}}{\|\mathbf{v}\|\|\mathbf{w}\|}\right).\]

In short, for these two specific vectors, the dot product combined with the norms tell us the angle between the two vectors. This same fact is true in general. We will not derive the expression here, however, if we consider writing \(\|\mathbf{v} - \mathbf{w}\|^2\) in two ways: one with the dot product, and the other geometrically using the law of cosines, we can obtain the full relationship. Indeed, for any two vectors \(\mathbf{v}\) and \(\mathbf{w}\), the angle between the two vectors is

(22.1.8)\[\theta = \arccos\left(\frac{\mathbf{v}\cdot\mathbf{w}}{\|\mathbf{v}\|\|\mathbf{w}\|}\right).\]

This is a nice result since nothing in the computation references two-dimensions. Indeed, we can use this in three or three million dimensions without issue.

As a simple example, let’s see how to compute the angle between a pair of vectors:

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


def angle(v, w):
    return torch.acos(v.dot(w) / (torch.norm(v) * torch.norm(w)))

angle(torch.tensor([0, 1, 2], dtype=torch.float32), torch.tensor([2.0, 3, 4]))
tensor(0.4190)

We will not use it right now, but it is useful to know that we will refer to vectors for which the angle is \(\pi/2\) (or equivalently \(90^{\circ}\)) as being orthogonal. By examining the equation above, we see that this happens when \(\theta = \pi/2\), which is the same thing as \(\cos(\theta) = 0\). The only way this can happen is if the dot product itself is zero, and two vectors are orthogonal if and only if \(\mathbf{v}\cdot\mathbf{w} = 0\). This will prove to be a helpful formula when understanding objects geometrically.

It is reasonable to ask: why is computing the angle useful? The answer comes in the kind of invariance we expect data to have. Consider an image, and a duplicate image, where every pixel value is the same but \(10\%\) the brightness. The values of the individual pixels are in general far from the original values. Thus, if one computed the distance between the original image and the darker one, the distance can be large. However, for most ML applications, the content is the same—it is still an image of a cat as far as a cat/dog classifier is concerned. However, if we consider the angle, it is not hard to see that for any vector \(\mathbf{v}\), the angle between \(\mathbf{v}\) and \(0.1\cdot\mathbf{v}\) is zero. This corresponds to the fact that scaling vectors keeps the same direction and just changes the length. The angle considers the darker image identical.

Examples like this are everywhere. In text, we might want the topic being discussed to not change if we write twice as long of document that says the same thing. For some encoding (such as counting the number of occurrences of words in some vocabulary), this corresponds to a doubling of the vector encoding the document, so again we can use the angle.

22.1.2.1. Cosine Similarity

In ML contexts where the angle is employed to measure the closeness of two vectors, practitioners adopt the term cosine similarity to refer to the portion

(22.1.9)\[\cos(\theta) = \frac{\mathbf{v}\cdot\mathbf{w}}{\|\mathbf{v}\|\|\mathbf{w}\|}.\]

The cosine takes a maximum value of \(1\) when the two vectors point in the same direction, a minimum value of \(-1\) when they point in opposite directions, and a value of \(0\) when the two vectors are orthogonal. Note that if the components of high-dimensional vectors are sampled randomly with mean \(0\), their cosine will nearly always be close to \(0\).

22.1.3. Hyperplanes

In addition to working with vectors, another key object that you must understand to go far in linear algebra is the hyperplane, a generalization to higher dimensions of a line (two dimensions) or of a plane (three dimensions). In an \(d\)-dimensional vector space, a hyperplane has \(d-1\) dimensions and divides the space into two half-spaces.

Let’s start with an example. Suppose that we have a column vector \(\mathbf{w}=[2,1]^\top\). We want to know, “what are the points \(\mathbf{v}\) with \(\mathbf{w}\cdot\mathbf{v} = 1\)?” By recalling the connection between dot products and angles above (22.1.8), we can see that this is equivalent to

(22.1.10)\[\|\mathbf{v}\|\|\mathbf{w}\|\cos(\theta) = 1 \; \iff \; \|\mathbf{v}\|\cos(\theta) = \frac{1}{\|\mathbf{w}\|} = \frac{1}{\sqrt{5}}.\]
../_images/proj-vec.svg

Fig. 22.1.5 Recalling trigonometry, we see the formula \(\|\mathbf{v}\|\cos(\theta)\) is the length of the projection of the vector \(\mathbf{v}\) onto the direction of \(\mathbf{w}\)

If we consider the geometric meaning of this expression, we see that this is equivalent to saying that the length of the projection of \(\mathbf{v}\) onto the direction of \(\mathbf{w}\) is exactly \(1/\|\mathbf{w}\|\), as is shown in Fig. 22.1.5. The set of all points where this is true is a line at right angles to the vector \(\mathbf{w}\). If we wanted, we could find the equation for this line and see that it is \(2x + y = 1\) or equivalently \(y = 1 - 2x\).

If we now look at what happens when we ask about the set of points with \(\mathbf{w}\cdot\mathbf{v} > 1\) or \(\mathbf{w}\cdot\mathbf{v} < 1\), we can see that these are cases where the projections are longer or shorter than \(1/\|\mathbf{w}\|\), respectively. Thus, those two inequalities define either side of the line. In this way, we have found a way to cut our space into two halves, where all the points on one side have dot product below a threshold, and the other side above as we see in Fig. 22.1.6.

../_images/space-division.svg

Fig. 22.1.6 If we now consider the inequality version of the expression, we see that our hyperplane (in this case: just a line) separates the space into two halves.

The story in higher dimension is much the same. If we now take \(\mathbf{w} = [1,2,3]^\top\) and ask about the points in three dimensions with \(\mathbf{w}\cdot\mathbf{v} = 1\), we obtain a plane at right angles to the given vector \(\mathbf{w}\). The two inequalities again define the two sides of the plane as is shown in Fig. 22.1.7.

../_images/space-division-3d.svg

Fig. 22.1.7 Hyperplanes in any dimension separate the space into two halves.

While our ability to visualize runs out at this point, nothing stops us from doing this in tens, hundreds, or billions of dimensions. This occurs often when thinking about machine learned models. For instance, we can understand linear classification models like those from Section 4.1, as methods to find hyperplanes that separate the different target classes. In this context, such hyperplanes are often referred to as decision planes. The majority of deep learned classification models end with a linear layer fed into a softmax, so one can interpret the role of the deep neural network to be to find a non-linear embedding such that the target classes can be separated cleanly by hyperplanes.

To give a hand-built example, notice that we can produce a reasonable model to classify tiny images of t-shirts and trousers from the Fashion-MNIST dataset (seen in Section 4.2) by just taking the vector between their means to define the decision plane and eyeball a crude threshold. First we will load the data and compute the averages.

# Load in the dataset
trans = []
trans.append(transforms.ToTensor())
trans = transforms.Compose(trans)
train = torchvision.datasets.FashionMNIST(root="../data", transform=trans,
                                          train=True, download=True)
test = torchvision.datasets.FashionMNIST(root="../data", transform=trans,
                                         train=False, download=True)

X_train_0 = torch.stack(
    [x[0] * 256 for x in train if x[1] == 0]).type(torch.float32)
X_train_1 = torch.stack(
    [x[0] * 256 for x in train if x[1] == 1]).type(torch.float32)
X_test = torch.stack(
    [x[0] * 256 for x in test if x[1] == 0 or x[1] == 1]).type(torch.float32)
y_test = torch.stack([torch.tensor(x[1]) for x in test
                      if x[1] == 0 or x[1] == 1]).type(torch.float32)

# Compute averages
ave_0 = torch.mean(X_train_0, axis=0)
ave_1 = torch.mean(X_train_1, axis=0)

It can be informative to examine these averages in detail, so let’s plot what they look like. In this case, we see that the average indeed resembles a blurry image of a t-shirt.

# Plot average t-shirt
d2l.set_figsize()
d2l.plt.imshow(ave_0.reshape(28, 28).tolist(), cmap='Greys')
d2l.plt.show()
../_images/output_geometry-linear-algebraic-ops_80b1c3_39_0.svg

In the second case, we again see that the average resembles a blurry image of trousers.

# Plot average trousers
d2l.plt.imshow(ave_1.reshape(28, 28).tolist(), cmap='Greys')
d2l.plt.show()
../_images/output_geometry-linear-algebraic-ops_80b1c3_51_0.svg

In a fully machine learned solution, we would learn the threshold from the dataset. In this case, I simply eyeballed a threshold that looked good on the training data by hand.

# Print test set accuracy with eyeballed threshold
w = (ave_1 - ave_0).T
# '@' is Matrix Multiplication operator in pytorch.
predictions = X_test.reshape(2000, -1) @ (w.flatten()) > -1500000

# Accuracy
torch.mean((predictions.type(y_test.dtype) == y_test).float(), dtype=torch.float64)
tensor(0.7870, dtype=torch.float64)

22.1.4. Geometry of Linear Transformations

Through Section 2.3 and the above discussions, we have a solid understanding of the geometry of vectors, lengths, and angles. However, there is one important object we have omitted discussing, and that is a geometric understanding of linear transformations represented by matrices. Fully internalizing what matrices can do to transform data between two potentially different high dimensional spaces takes significant practice, and is beyond the scope of this appendix. However, we can start building up intuition in two dimensions.

Suppose that we have some matrix:

(22.1.11)\[\begin{split}\mathbf{A} = \begin{bmatrix} a & b \\ c & d \end{bmatrix}.\end{split}\]

If we want to apply this to an arbitrary vector \(\mathbf{v} = [x, y]^\top\), we multiply and see that

(22.1.12)\[\begin{split}\begin{aligned} \mathbf{A}\mathbf{v} & = \begin{bmatrix}a & b \\ c & d\end{bmatrix}\begin{bmatrix}x \\ y\end{bmatrix} \\ & = \begin{bmatrix}ax+by\\ cx+dy\end{bmatrix} \\ & = x\begin{bmatrix}a \\ c\end{bmatrix} + y\begin{bmatrix}b \\d\end{bmatrix} \\ & = x\left\{\mathbf{A}\begin{bmatrix}1\\0\end{bmatrix}\right\} + y\left\{\mathbf{A}\begin{bmatrix}0\\1\end{bmatrix}\right\}. \end{aligned}\end{split}\]

This may seem like an odd computation, where something clear became somewhat impenetrable. However, it tells us that we can write the way that a matrix transforms any vector in terms of how it transforms two specific vectors: \([1,0]^\top\) and \([0,1]^\top\). This is worth considering for a moment. We have essentially reduced an infinite problem (what happens to any pair of real numbers) to a finite one (what happens to these specific vectors). These vectors are an example a basis, where we can write any vector in our space as a weighted sum of these basis vectors.

Let’s draw what happens when we use the specific matrix

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

If we look at the specific vector \(\mathbf{v} = [2, -1]^\top\), we see this is \(2\cdot[1,0]^\top + -1\cdot[0,1]^\top\), and thus we know that the matrix \(A\) will send this to \(2(\mathbf{A}[1,0]^\top) + -1(\mathbf{A}[0,1])^\top = 2[1, -1]^\top - [2,3]^\top = [0, -5]^\top\). If we follow this logic through carefully, say by considering the grid of all integer pairs of points, we see that what happens is that the matrix multiplication can skew, rotate, and scale the grid, but the grid structure must remain as you see in Fig. 22.1.8.

../_images/grid-transform.svg

Fig. 22.1.8 The matrix \(\mathbf{A}\) acting on the given basis vectors. Notice how the entire grid is transported along with it.

This is the most important intuitive point to internalize about linear transformations represented by matrices. Matrices are incapable of distorting some parts of space differently than others. All they can do is take the original coordinates on our space and skew, rotate, and scale them.

Some distortions can be severe. For instance the matrix

(22.1.14)\[\begin{split}\mathbf{B} = \begin{bmatrix} 2 & -1 \\ 4 & -2 \end{bmatrix},\end{split}\]

compresses the entire two-dimensional plane down to a single line. Identifying and working with such transformations are the topic of a later section, but geometrically we can see that this is fundamentally different from the types of transformations we saw above. For instance, the result from matrix \(\mathbf{A}\) can be “bent back” to the original grid. The results from matrix \(\mathbf{B}\) cannot because we will never know where the vector \([1,2]^\top\) came from—was it \([1,1]^\top\) or \([0, -1]^\top\)?

While this picture was for a \(2\times2\) matrix, nothing prevents us from taking the lessons learned into higher dimensions. If we take similar basis vectors like \([1,0, \ldots,0]\) and see where our matrix sends them, we can start to get a feeling for how the matrix multiplication distorts the entire space in whatever dimension space we are dealing with.

22.1.5. Linear Dependence

Consider again the matrix

(22.1.15)\[\begin{split}\mathbf{B} = \begin{bmatrix} 2 & -1 \\ 4 & -2 \end{bmatrix}.\end{split}\]

This compresses the entire plane down to live on the single line \(y = 2x\). The question now arises: is there some way we can detect this just looking at the matrix itself? The answer is that indeed we can. Let’s take \(\mathbf{b}_1 = [2,4]^\top\) and \(\mathbf{b}_2 = [-1, -2]^\top\) be the two columns of \(\mathbf{B}\). Remember that we can write everything transformed by the matrix \(\mathbf{B}\) as a weighted sum of the columns of the matrix: like \(a_1\mathbf{b}_1 + a_2\mathbf{b}_2\). We call this a linear combination. The fact that \(\mathbf{b}_1 = -2\cdot\mathbf{b}_2\) means that we can write any linear combination of those two columns entirely in terms of say \(\mathbf{b}_2\) since

(22.1.16)\[a_1\mathbf{b}_1 + a_2\mathbf{b}_2 = -2a_1\mathbf{b}_2 + a_2\mathbf{b}_2 = (a_2-2a_1)\mathbf{b}_2.\]

This means that one of the columns is, in a sense, redundant because it does not define a unique direction in space. This should not surprise us too much since we already saw that this matrix collapses the entire plane down into a single line. Moreover, we see that the linear dependence \(\mathbf{b}_1 = -2\cdot\mathbf{b}_2\) captures this. To make this more symmetrical between the two vectors, we will write this as

(22.1.17)\[\mathbf{b}_1 + 2\cdot\mathbf{b}_2 = 0.\]

In general, we will say that a collection of vectors \(\mathbf{v}_1, \ldots, \mathbf{v}_k\) are linearly dependent if there exist coefficients \(a_1, \ldots, a_k\) not all equal to zero so that

(22.1.18)\[\sum_{i=1}^k a_i\mathbf{v_i} = 0.\]

In this case, we can solve for one of the vectors in terms of some combination of the others, and effectively render it redundant. Thus, a linear dependence in the columns of a matrix is a witness to the fact that our matrix is compressing the space down to some lower dimension. If there is no linear dependence we say the vectors are linearly independent. If the columns of a matrix are linearly independent, no compression occurs and the operation can be undone.

22.1.6. Rank

If we have a general \(n\times m\) matrix, it is reasonable to ask what dimension space the matrix maps into. A concept known as the rank will be our answer. In the previous section, we noted that a linear dependence bears witness to compression of space into a lower dimension and so we will be able to use this to define the notion of rank. In particular, the rank of a matrix \(\mathbf{A}\) is the largest number of linearly independent columns amongst all subsets of columns. For example, the matrix

(22.1.19)\[\begin{split}\mathbf{B} = \begin{bmatrix} 2 & 4 \\ -1 & -2 \end{bmatrix},\end{split}\]

has \(\textrm{rank}(B)=1\), since the two columns are linearly dependent, but either column by itself is not linearly dependent. For a more challenging example, we can consider

(22.1.20)\[\begin{split}\mathbf{C} = \begin{bmatrix} 1& 3 & 0 & -1 & 0 \\ -1 & 0 & 1 & 1 & -1 \\ 0 & 3 & 1 & 0 & -1 \\ 2 & 3 & -1 & -2 & 1 \end{bmatrix},\end{split}\]

and show that \(\mathbf{C}\) has rank two since, for instance, the first two columns are linearly independent, however any of the four collections of three columns are dependent.

This procedure, as described, is very inefficient. It requires looking at every subset of the columns of our given matrix, and thus is potentially exponential in the number of columns. Later we will see a more computationally efficient way to compute the rank of a matrix, but for now, this is sufficient to see that the concept is well defined and understand the meaning.

22.1.7. Invertibility

We have seen above that multiplication by a matrix with linearly dependent columns cannot be undone, i.e., there is no inverse operation that can always recover the input. However, multiplication by a full-rank matrix (i.e., some \(\mathbf{A}\) that is \(n \times n\) matrix with rank \(n\)), we should always be able to undo it. Consider the matrix

(22.1.21)\[\begin{split}\mathbf{I} = \begin{bmatrix} 1 & 0 & \cdots & 0 \\ 0 & 1 & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & 1 \end{bmatrix}.\end{split}\]

which is the matrix with ones along the diagonal, and zeros elsewhere. We call this the identity matrix. It is the matrix which leaves our data unchanged when applied. To find a matrix which undoes what our matrix \(\mathbf{A}\) has done, we want to find a matrix \(\mathbf{A}^{-1}\) such that

(22.1.22)\[\mathbf{A}^{-1}\mathbf{A} = \mathbf{A}\mathbf{A}^{-1} = \mathbf{I}.\]

If we look at this as a system, we have \(n \times n\) unknowns (the entries of \(\mathbf{A}^{-1}\)) and \(n \times n\) equations (the equality that needs to hold between every entry of the product \(\mathbf{A}^{-1}\mathbf{A}\) and every entry of \(\mathbf{I}\)) so we should generically expect a solution to exist. Indeed, in the next section we will see a quantity called the determinant, which has the property that as long as the determinant is not zero, we can find a solution. We call such a matrix \(\mathbf{A}^{-1}\) the inverse matrix. As an example, if \(\mathbf{A}\) is the general \(2 \times 2\) matrix

(22.1.23)\[\begin{split}\mathbf{A} = \begin{bmatrix} a & b \\ c & d \end{bmatrix},\end{split}\]

then we can see that the inverse is

(22.1.24)\[\begin{split} \frac{1}{ad-bc} \begin{bmatrix} d & -b \\ -c & a \end{bmatrix}.\end{split}\]

We can test to see this by seeing that multiplying by the inverse given by the formula above works in practice.

M = torch.tensor([[1, 2], [1, 4]], dtype=torch.float32)
M_inv = torch.tensor([[2, -1], [-0.5, 0.5]])
M_inv @ M
tensor([[1., 0.],
        [0., 1.]])

22.1.7.1. Numerical Issues

While the inverse of a matrix is useful in theory, we must say that most of the time we do not wish to use the matrix inverse to solve a problem in practice. In general, there are far more numerically stable algorithms for solving linear equations like

(22.1.25)\[\mathbf{A}\mathbf{x} = \mathbf{b},\]

than computing the inverse and multiplying to get

(22.1.26)\[\mathbf{x} = \mathbf{A}^{-1}\mathbf{b}.\]

Just as division by a small number can lead to numerical instability, so can inversion of a matrix which is close to having low rank.

Moreover, it is common that the matrix \(\mathbf{A}\) is sparse, which is to say that it contains only a small number of non-zero values. If we were to explore examples, we would see that this does not mean the inverse is sparse. Even if \(\mathbf{A}\) was a \(1\) million by \(1\) million matrix with only \(5\) million non-zero entries (and thus we need only store those \(5\) million), the inverse will typically have almost every entry non-negative, requiring us to store all \(1\textrm{M}^2\) entries—that is \(1\) trillion entries!

While we do not have time to dive all the way into the thorny numerical issues frequently encountered when working with linear algebra, we want to provide you with some intuition about when to proceed with caution, and generally avoiding inversion in practice is a good rule of thumb.

22.1.8. Determinant

The geometric view of linear algebra gives an intuitive way to interpret a fundamental quantity known as the determinant. Consider the grid image from before, but now with a highlighted region (Fig. 22.1.9).

../_images/grid-transform-filled.svg

Fig. 22.1.9 The matrix \(\mathbf{A}\) again distorting the grid. This time, I want to draw particular attention to what happens to the highlighted square.

Look at the highlighted square. This is a square with edges given by \((0, 1)\) and \((1, 0)\) and thus it has area one. After \(\mathbf{A}\) transforms this square, we see that it becomes a parallelogram. There is no reason this parallelogram should have the same area that we started with, and indeed in the specific case shown here of

(22.1.27)\[\begin{split}\mathbf{A} = \begin{bmatrix} 1 & 2 \\ -1 & 3 \end{bmatrix},\end{split}\]

it is an exercise in coordinate geometry to compute the area of this parallelogram and obtain that the area is \(5\).

In general, if we have a matrix

(22.1.28)\[\begin{split}\mathbf{A} = \begin{bmatrix} a & b \\ c & d \end{bmatrix},\end{split}\]

we can see with some computation that the area of the resulting parallelogram is \(ad-bc\). This area is referred to as the determinant.

Let’s check this quickly with some example code.

torch.det(torch.tensor([[1, -1], [2, 3]], dtype=torch.float32))
tensor(5.)

The eagle-eyed amongst us will notice that this expression can be zero or even negative. For the negative term, this is a matter of convention taken generally in mathematics: if the matrix flips the figure, we say the area is negated. Let’s see now that when the determinant is zero, we learn more.

Let’s consider

(22.1.29)\[\begin{split}\mathbf{B} = \begin{bmatrix} 2 & 4 \\ -1 & -2 \end{bmatrix}.\end{split}\]

If we compute the determinant of this matrix, we get \(2\cdot(-2 ) - 4\cdot(-1) = 0\). Given our understanding above, this makes sense. \(\mathbf{B}\) compresses the square from the original image down to a line segment, which has zero area. And indeed, being compressed into a lower dimensional space is the only way to have zero area after the transformation. Thus we see the following result is true: a matrix \(A\) is invertible if and only if the determinant is not equal to zero.

As a final comment, imagine that we have any figure drawn on the plane. Thinking like computer scientists, we can decompose that figure into a collection of little squares so that the area of the figure is in essence just the number of squares in the decomposition. If we now transform that figure by a matrix, we send each of these squares to parallelograms, each one of which has area given by the determinant. We see that for any figure, the determinant gives the (signed) number that a matrix scales the area of any figure.

Computing determinants for larger matrices can be laborious, but the intuition is the same. The determinant remains the factor that \(n\times n\) matrices scale \(n\)-dimensional volumes.

22.1.9. Tensors and Common Linear Algebra Operations

In Section 2.3 the concept of tensors was introduced. In this section, we will dive more deeply into tensor contractions (the tensor equivalent of matrix multiplication), and see how it can provide a unified view on a number of matrix and vector operations.

With matrices and vectors we knew how to multiply them to transform data. We need to have a similar definition for tensors if they are to be useful to us. Think about matrix multiplication:

(22.1.30)\[\mathbf{C} = \mathbf{A}\mathbf{B},\]

or equivalently

(22.1.31)\[c_{i, j} = \sum_{k} a_{i, k}b_{k, j}.\]

This pattern is one we can repeat for tensors. For tensors, there is no one case of what to sum over that can be universally chosen, so we need specify exactly which indices we want to sum over. For instance we could consider

(22.1.32)\[y_{il} = \sum_{jk} x_{ijkl}a_{jk}.\]

Such a transformation is called a tensor contraction. It can represent a far more flexible family of transformations that matrix multiplication alone.

As a often-used notational simplification, we can notice that the sum is over exactly those indices that occur more than once in the expression, thus people often work with Einstein notation, where the summation is implicitly taken over all repeated indices. This gives the compact expression:

(22.1.33)\[y_{il} = x_{ijkl}a_{jk}.\]

22.1.9.1. Common Examples from Linear Algebra

Let’s see how many of the linear algebraic definitions we have seen before can be expressed in this compressed tensor notation:

  • \(\mathbf{v} \cdot \mathbf{w} = \sum_i v_iw_i\)

  • \(\|\mathbf{v}\|_2^{2} = \sum_i v_iv_i\)

  • \((\mathbf{A}\mathbf{v})_i = \sum_j a_{ij}v_j\)

  • \((\mathbf{A}\mathbf{B})_{ik} = \sum_j a_{ij}b_{jk}\)

  • \(\textrm{tr}(\mathbf{A}) = \sum_i a_{ii}\)

In this way, we can replace a myriad of specialized notations with short tensor expressions.

22.1.9.2. Expressing in Code

Tensors may flexibly be operated on in code as well. As seen in Section 2.3, we can create tensors as is shown below.

# Define tensors
B = torch.tensor([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
A = torch.tensor([[1, 2], [3, 4]])
v = torch.tensor([1, 2])

# Print out the shapes
A.shape, B.shape, v.shape
(torch.Size([2, 2]), torch.Size([2, 2, 3]), torch.Size([2]))

Einstein summation has been implemented directly. The indices that occurs in the Einstein summation can be passed as a string, followed by the tensors that are being acted upon. For instance, to implement matrix multiplication, we can consider the Einstein summation seen above (\(\mathbf{A}\mathbf{v} = a_{ij}v_j\)) and strip out the indices themselves to get the implementation:

# Reimplement matrix multiplication
torch.einsum("ij, j -> i", A, v), A@v
(tensor([ 5, 11]), tensor([ 5, 11]))

This is a highly flexible notation. For instance if we want to compute what would be traditionally written as

(22.1.34)\[c_{kl} = \sum_{ij} \mathbf{b}_{ijk}\mathbf{a}_{il}v_j.\]

it can be implemented via Einstein summation as:

torch.einsum("ijk, il, j -> kl", B, A, v)
tensor([[ 90, 126],
        [102, 144],
        [114, 162]])

This notation is readable and efficient for humans, however bulky if for whatever reason we need to generate a tensor contraction programmatically. For this reason, einsum provides an alternative notation by providing integer indices for each tensor. For example, the same tensor contraction can also be written as:

# PyTorch does not support this type of notation.

Either notation allows for concise and efficient representation of tensor contractions in code.

22.1.10. Summary

  • Vectors can be interpreted geometrically as either points or directions in space.

  • Dot products define the notion of angle to arbitrarily high-dimensional spaces.

  • Hyperplanes are high-dimensional generalizations of lines and planes. They can be used to define decision planes that are often used as the last step in a classification task.

  • Matrix multiplication can be geometrically interpreted as uniform distortions of the underlying coordinates. They represent a very restricted, but mathematically clean, way to transform vectors.

  • Linear dependence is a way to tell when a collection of vectors are in a lower dimensional space than we would expect (say you have \(3\) vectors living in a \(2\)-dimensional space). The rank of a matrix is the size of the largest subset of its columns that are linearly independent.

  • When a matrix’s inverse is defined, matrix inversion allows us to find another matrix that undoes the action of the first. Matrix inversion is useful in theory, but requires care in practice owing to numerical instability.

  • Determinants allow us to measure how much a matrix expands or contracts a space. A nonzero determinant implies an invertible (non-singular) matrix and a zero-valued determinant means that the matrix is non-invertible (singular).

  • Tensor contractions and Einstein summation provide for a neat and clean notation for expressing many of the computations that are seen in machine learning.

22.1.11. Exercises

  1. What is the angle between

    (22.1.35)\[\begin{split}\vec v_1 = \begin{bmatrix} 1 \\ 0 \\ -1 \\ 2 \end{bmatrix}, \qquad \vec v_2 = \begin{bmatrix} 3 \\ 1 \\ 0 \\ 1 \end{bmatrix}?\end{split}\]
  2. True or false: \(\begin{bmatrix}1 & 2\\0&1\end{bmatrix}\) and \(\begin{bmatrix}1 & -2\\0&1\end{bmatrix}\) are inverses of one another?

  3. Suppose that we draw a shape in the plane with area \(100\textrm{m}^2\). What is the area after transforming the figure by the matrix

    (22.1.36)\[\begin{split}\begin{bmatrix} 2 & 3\\ 1 & 2 \end{bmatrix}.\end{split}\]
  4. Which of the following sets of vectors are linearly independent?

  • \(\left\{\begin{pmatrix}1\\0\\-1\end{pmatrix}, \begin{pmatrix}2\\1\\-1\end{pmatrix}, \begin{pmatrix}3\\1\\1\end{pmatrix}\right\}\)

  • \(\left\{\begin{pmatrix}3\\1\\1\end{pmatrix}, \begin{pmatrix}1\\1\\1\end{pmatrix}, \begin{pmatrix}0\\0\\0\end{pmatrix}\right\}\)

  • \(\left\{\begin{pmatrix}1\\1\\0\end{pmatrix}, \begin{pmatrix}0\\1\\-1\end{pmatrix}, \begin{pmatrix}1\\0\\1\end{pmatrix}\right\}\)

  1. Suppose that you have a matrix written as \(A = \begin{bmatrix}c\\d\end{bmatrix}\cdot\begin{bmatrix}a & b\end{bmatrix}\) for some choice of values \(a, b, c\), and \(d\). True or false: the determinant of such a matrix is always \(0\)?

  2. The vectors \(e_1 = \begin{bmatrix}1\\0\end{bmatrix}\) and \(e_2 = \begin{bmatrix}0\\1\end{bmatrix}\) are orthogonal. What is the condition on a matrix \(A\) so that \(Ae_1\) and \(Ae_2\) are orthogonal?

  3. How can you write \(\textrm{tr}(\mathbf{A}^4)\) in Einstein notation for an arbitrary matrix \(A\)?

8.1. Pipelines and composite estimators

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.1. Pipelines and composite estimators

To build a composite estimator, transformers are usually combined with other transformers or with predictors (such as classifiers or regressors). The most common tool used for composing estimators is a Pipeline. Pipelines require all steps except the last to be a transformer. The last step can be anything, a transformer, a predictor, or a clustering estimator which might have or not have a .predict(...) method. A pipeline exposes all methods provided by the last estimator: if the last step provides a transform method, then the pipeline would have a transform method and behave like a transformer. If the last step provides a predict method, then the pipeline would expose that method, and given a data X, use all steps except the last to transform the data, and then give that transformed data to the predict method of the last step of the pipeline. The class Pipeline is often used in combination with ColumnTransformer or FeatureUnion which concatenate the output of transformers into a composite feature space. TransformedTargetRegressor deals with transforming the target (i.e. log-transform y).

8.1.1. Pipeline: chaining estimators

Pipeline can be used to chain multiple estimators into one. This is useful as there is often a fixed sequence of steps in processing the data, for example feature selection, normalization and classification. Pipeline serves multiple purposes here:

Convenience and encapsulation

You only have to call fit and predict once on your data to fit a whole sequence of estimators.

Joint parameter selection

You can grid search over parameters of all estimators in the pipeline at once.

Safety

Pipelines help avoid leaking statistics from your test data into the trained model in cross-validation, by ensuring that the same samples are used to train the transformers and predictors.

All estimators in a pipeline, except the last one, must be transformers (i.e. must have a transform method). The last estimator may be any type (transformer, classifier, etc.).

Note

Calling fit on the pipeline is the same as calling fit on each estimator in turn, transform the input and pass it on to the next step. The pipeline has all the methods that the last estimator in the pipeline has, i.e. if the last estimator is a classifier, the Pipeline can be used as a classifier. If the last estimator is a transformer, again, so is the pipeline.

8.1.1.1. Usage

8.1.1.1.1. Build a pipeline

The Pipeline is built using a list of (key, value) pairs, where the key is a string containing the name you want to give this step and value is an estimator object:

>>> from sklearn.pipeline import Pipeline
>>> from sklearn.svm import SVC
>>> from sklearn.decomposition import PCA
>>> estimators = [('reduce_dim', PCA()), ('clf', SVC())]
>>> pipe = Pipeline(estimators)
>>> pipe
Pipeline(steps=[('reduce_dim', PCA()), ('clf', SVC())])
Shorthand version using make_pipeline

The utility function make_pipeline is a shorthand for constructing pipelines; it takes a variable number of estimators and returns a pipeline, filling in the names automatically:

>>> from sklearn.pipeline import make_pipeline
>>> make_pipeline(PCA(), SVC())
Pipeline(steps=[('pca', PCA()), ('svc', SVC())])

8.1.1.1.2. Access pipeline steps

The estimators of a pipeline are stored as a list in the steps attribute. A sub-pipeline can be extracted using the slicing notation commonly used for Python Sequences such as lists or strings (although only a step of 1 is permitted). This is convenient for performing only some of the transformations (or their inverse):

>>> pipe[:1]
Pipeline(steps=[('reduce_dim', PCA())])
>>> pipe[-1:]
Pipeline(steps=[('clf', SVC())])
Accessing a step by name or position

A specific step can also be accessed by index or name by indexing (with [idx]) the pipeline:

>>> pipe.steps[0]
('reduce_dim', PCA())
>>> pipe[0]
PCA()
>>> pipe['reduce_dim']
PCA()

Pipeline’s named_steps attribute allows accessing steps by name with tab completion in interactive environments:

>>> pipe.named_steps.reduce_dim is pipe['reduce_dim']
True

8.1.1.1.3. Tracking feature names in a pipeline

To enable model inspection, Pipeline has a get_feature_names_out() method, just like all transformers. You can use pipeline slicing to get the feature names going into each step:

>>> from sklearn.datasets import load_iris
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.feature_selection import SelectKBest
>>> iris = load_iris()
>>> pipe = Pipeline(steps=[
...    ('select', SelectKBest(k=2)),
...    ('clf', LogisticRegression())])
>>> pipe.fit(iris.data, iris.target)
Pipeline(steps=[('select', SelectKBest(...)), ('clf', LogisticRegression(...))])
>>> pipe[:-1].get_feature_names_out()
array(['x2', 'x3'], ...)
Customize feature names

You can also provide custom feature names for the input data using get_feature_names_out:

>>> pipe[:-1].get_feature_names_out(iris.feature_names)
array(['petal length (cm)', 'petal width (cm)'], ...)

8.1.1.1.4. Access to nested parameters

It is common to adjust the parameters of an estimator within a pipeline. This parameter is therefore nested because it belongs to a particular sub-step. Parameters of the estimators in the pipeline are accessible using the <estimator>__<parameter> syntax:

>>> pipe = Pipeline(steps=[("reduce_dim", PCA()), ("clf", SVC())])
>>> pipe.set_params(clf__C=10)
Pipeline(steps=[('reduce_dim', PCA()), ('clf', SVC(C=10))])
When does it matter?

This is particularly important for doing grid searches:

>>> from sklearn.model_selection import GridSearchCV
>>> param_grid = dict(reduce_dim__n_components=[2, 5, 10],
...                   clf__C=[0.1, 10, 100])
>>> grid_search = GridSearchCV(pipe, param_grid=param_grid)

Individual steps may also be replaced as parameters, and non-final steps may be ignored by setting them to 'passthrough':

>>> param_grid = dict(reduce_dim=['passthrough', PCA(5), PCA(10)],
...                   clf=[SVC(), LogisticRegression()],
...                   clf__C=[0.1, 10, 100])
>>> grid_search = GridSearchCV(pipe, param_grid=param_grid)

Examples

8.1.1.2. Caching transformers: avoid repeated computation

Fitting transformers may be computationally expensive. With its memory parameter set, Pipeline will cache each transformer after calling fit. This feature is used to avoid computing the fit transformers within a pipeline if the parameters and input data are identical. A typical example is the case of a grid search in which the transformers can be fitted only once and reused for each configuration. The last step will never be cached, even if it is a transformer.

The parameter memory is needed in order to cache the transformers. memory can be either a string containing the directory where to cache the transformers or a joblib.Memory object:

>>> from tempfile import mkdtemp
>>> from shutil import rmtree
>>> from sklearn.decomposition import PCA
>>> from sklearn.svm import SVC
>>> from sklearn.pipeline import Pipeline
>>> estimators = [('reduce_dim', PCA()), ('clf', SVC())]
>>> cachedir = mkdtemp()
>>> pipe = Pipeline(estimators, memory=cachedir)
>>> pipe
Pipeline(memory=...,
         steps=[('reduce_dim', PCA()), ('clf', SVC())])
>>> # Clear the cache directory when you don't need it anymore
>>> rmtree(cachedir)
Side effect of caching transformers

Using a Pipeline without cache enabled, it is possible to inspect the original instance such as:

>>> from sklearn.datasets import load_digits
>>> X_digits, y_digits = load_digits(return_X_y=True)
>>> pca1 = PCA(n_components=10)
>>> svm1 = SVC()
>>> pipe = Pipeline([('reduce_dim', pca1), ('clf', svm1)])
>>> pipe.fit(X_digits, y_digits)
Pipeline(steps=[('reduce_dim', PCA(n_components=10)), ('clf', SVC())])
>>> # The pca instance can be inspected directly
>>> pca1.components_.shape
(10, 64)

Enabling caching triggers a clone of the transformers before fitting. Therefore, the transformer instance given to the pipeline cannot be inspected directly. In the following example, accessing the PCA instance pca2 will raise an AttributeError since pca2 will be an unfitted transformer. Instead, use the attribute named_steps to inspect estimators within the pipeline:

>>> cachedir = mkdtemp()
>>> pca2 = PCA(n_components=10)
>>> svm2 = SVC()
>>> cached_pipe = Pipeline([('reduce_dim', pca2), ('clf', svm2)],
...                        memory=cachedir)
>>> cached_pipe.fit(X_digits, y_digits)
Pipeline(memory=...,
         steps=[('reduce_dim', PCA(n_components=10)), ('clf', SVC())])
>>> cached_pipe.named_steps['reduce_dim'].components_.shape
(10, 64)
>>> # Remove the cache directory
>>> rmtree(cachedir)

Examples

8.1.2. Transforming target in regression

TransformedTargetRegressor transforms the targets y before fitting a regression model. The predictions are mapped back to the original space via an inverse transform. It takes as an argument the regressor that will be used for prediction, and the transformer that will be applied to the target variable:

>>> import numpy as np
>>> from sklearn.datasets import make_regression
>>> from sklearn.compose import TransformedTargetRegressor
>>> from sklearn.preprocessing import QuantileTransformer
>>> from sklearn.linear_model import LinearRegression
>>> from sklearn.model_selection import train_test_split
>>> # create a synthetic dataset
>>> X, y = make_regression(n_samples=20640,
...                        n_features=8,
...                        noise=100.0,
...                        random_state=0)
>>> y = np.exp( 1 + (y - y.min()) * (4 / (y.max() - y.min())))
>>> X, y = X[:2000, :], y[:2000]  # select a subset of data
>>> transformer = QuantileTransformer(output_distribution='normal')
>>> regressor = LinearRegression()
>>> regr = TransformedTargetRegressor(regressor=regressor,
...                                   transformer=transformer)
>>> X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
>>> regr.fit(X_train, y_train)
TransformedTargetRegressor(...)
>>> print(f"R2 score: {regr.score(X_test, y_test):.2f}")
R2 score: 0.67
>>> raw_target_regr = LinearRegression().fit(X_train, y_train)
>>> print(f"R2 score: {raw_target_regr.score(X_test, y_test):.2f}")
R2 score: 0.64

For simple transformations, instead of a Transformer object, a pair of functions can be passed, defining the transformation and its inverse mapping:

>>> def func(x):
...     return np.log(x)
>>> def inverse_func(x):
...     return np.exp(x)

Subsequently, the object is created as:

>>> regr = TransformedTargetRegressor(regressor=regressor,
...                                   func=func,
...                                   inverse_func=inverse_func)
>>> regr.fit(X_train, y_train)
TransformedTargetRegressor(...)
>>> print(f"R2 score: {regr.score(X_test, y_test):.2f}")
R2 score: 0.67

By default, the provided functions are checked at each fit to be the inverse of each other. However, it is possible to bypass this checking by setting check_inverse to False:

>>> def inverse_func(x):
...     return x
>>> regr = TransformedTargetRegressor(regressor=regressor,
...                                   func=func,
...                                   inverse_func=inverse_func,
...                                   check_inverse=False)
>>> regr.fit(X_train, y_train)
TransformedTargetRegressor(...)
>>> print(f"R2 score: {regr.score(X_test, y_test):.2f}")
R2 score: -3.02

Note

The transformation can be triggered by setting either transformer or the pair of functions func and inverse_func. However, setting both options will raise an error.

Examples

8.1.3. FeatureUnion: composite feature spaces

FeatureUnion combines several transformer objects into a new transformer that combines their output. A FeatureUnion takes a list of transformer objects. During fitting, each of these is fit to the data independently. The transformers are applied in parallel, and the feature matrices they output are concatenated side-by-side into a larger matrix.

When you want to apply different transformations to each field of the data, see the related class ColumnTransformer (see user guide).

FeatureUnion serves the same purposes as Pipeline - convenience and joint parameter estimation and validation.

FeatureUnion and Pipeline can be combined to create complex models.

(A FeatureUnion has no way of checking whether two transformers might produce identical features. It only produces a union when the feature sets are disjoint, and making sure they are is the caller’s responsibility.)

8.1.3.1. Usage

A FeatureUnion is built using a list of (key, value) pairs, where the key is the name you want to give to a given transformation (an arbitrary string; it only serves as an identifier) and value is an estimator object:

>>> from sklearn.pipeline import FeatureUnion
>>> from sklearn.decomposition import PCA
>>> from sklearn.decomposition import KernelPCA
>>> estimators = [('linear_pca', PCA()), ('kernel_pca', KernelPCA())]
>>> combined = FeatureUnion(estimators)
>>> combined
FeatureUnion(transformer_list=[('linear_pca', PCA()),
                               ('kernel_pca', KernelPCA())])

Like pipelines, feature unions have a shorthand constructor called make_union that does not require explicit naming of the components.

Like Pipeline, individual steps may be replaced using set_params, and ignored by setting to 'drop':

>>> combined.set_params(kernel_pca='drop')
FeatureUnion(transformer_list=[('linear_pca', PCA()),
                               ('kernel_pca', 'drop')])

Examples

8.1.4. ColumnTransformer for heterogeneous data

Many datasets contain features of different types, say text, floats, and dates, where each type of feature requires separate preprocessing or feature extraction steps. Often it is easiest to preprocess data before applying scikit-learn methods, for example using pandas. Processing your data before passing it to scikit-learn might be problematic for one of the following reasons:

  1. Incorporating statistics from test data into the preprocessors makes cross-validation scores unreliable (known as data leakage), for example in the case of scalers or imputing missing values.

  2. You may want to include the parameters of the preprocessors in a parameter search.

The ColumnTransformer helps performing different transformations for different columns of the data, within a Pipeline that is safe from data leakage and that can be parametrized. ColumnTransformer works on arrays, sparse matrices, and pandas DataFrames.

To each column, a different transformation can be applied, such as preprocessing or a specific feature extraction method:

>>> import pandas as pd
>>> X = pd.DataFrame(
...     {'city': ['London', 'London', 'Paris', 'Sallisaw'],
...      'title': ["His Last Bow", "How Watson Learned the Trick",
...                "A Moveable Feast", "The Grapes of Wrath"],
...      'expert_rating': [5, 3, 4, 5],
...      'user_rating': [4, 5, 4, 3]})

For this data, we might want to encode the 'city' column as a categorical variable using OneHotEncoder but apply a CountVectorizer to the 'title' column. As we might use multiple feature extraction methods on the same column, we give each transformer a unique name, say 'city_category' and 'title_bow'. By default, the remaining rating columns are ignored (remainder='drop'):

>>> from sklearn.compose import ColumnTransformer
>>> from sklearn.feature_extraction.text import CountVectorizer
>>> from sklearn.preprocessing import OneHotEncoder
>>> column_trans = ColumnTransformer(
...     [('categories', OneHotEncoder(dtype='int'), ['city']),
...      ('title_bow', CountVectorizer(), 'title')],
...     remainder='drop', verbose_feature_names_out=False)

>>> column_trans.fit(X)
ColumnTransformer(transformers=[('categories', OneHotEncoder(dtype='int'),
                                 ['city']),
                                ('title_bow', CountVectorizer(), 'title')],
                  verbose_feature_names_out=False)

>>> column_trans.get_feature_names_out()
array(['city_London', 'city_Paris', 'city_Sallisaw', 'bow', 'feast',
'grapes', 'his', 'how', 'last', 'learned', 'moveable', 'of', 'the',
 'trick', 'watson', 'wrath'], ...)

>>> column_trans.transform(X).toarray()
array([[1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0],
       [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1]]...)

In the above example, the CountVectorizer expects a 1D array as input and therefore the columns were specified as a string ('title'). However, OneHotEncoder as most of other transformers expects 2D data, therefore in that case you need to specify the column as a list of strings (['city']).

Apart from a scalar or a single item list, the column selection can be specified as a list of multiple items, an integer array, a slice, a boolean mask, or with a make_column_selector. The make_column_selector is used to select columns based on data type or column name:

>>> from sklearn.preprocessing import StandardScaler
>>> from sklearn.compose import make_column_selector
>>> ct = ColumnTransformer([
...       ('scale', StandardScaler(),
...       make_column_selector(dtype_include=np.number)),
...       ('onehot',
...       OneHotEncoder(),
...       make_column_selector(pattern='city', dtype_include=[object, "string"]))])
>>> ct.fit_transform(X)
array([[ 0.904,  0.      ,  1. ,  0. ,  0. ],
       [-1.507,  1.414,  1. ,  0. ,  0. ],
       [-0.301,  0.      ,  0. ,  1. ,  0. ],
       [ 0.904, -1.414,  0. ,  0. ,  1. ]])

Strings can reference columns if the input is a DataFrame, integers are always interpreted as the positional columns.

We can keep the remaining rating columns by setting remainder='passthrough'. The values are appended to the end of the transformation:

>>> column_trans = ColumnTransformer(
...     [('city_category', OneHotEncoder(dtype='int'),['city']),
...      ('title_bow', CountVectorizer(), 'title')],
...     remainder='passthrough')

>>> column_trans.fit_transform(X)
array([[1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 5, 4],
       [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 3, 5],
       [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 4, 4],
       [0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 5, 3]]...)

The remainder parameter can be set to an estimator to transform the remaining rating columns. The transformed values are appended to the end of the transformation:

>>> from sklearn.preprocessing import MinMaxScaler
>>> column_trans = ColumnTransformer(
...     [('city_category', OneHotEncoder(), ['city']),
...      ('title_bow', CountVectorizer(), 'title')],
...     remainder=MinMaxScaler())

>>> column_trans.fit_transform(X)[:, -2:]
array([[1. , 0.5],
       [0. , 1. ],
       [0.5, 0.5],
       [1. , 0. ]])

The make_column_transformer function is available to more easily create a ColumnTransformer object. Specifically, the names will be given automatically. The equivalent for the above example would be:

>>> from sklearn.compose import make_column_transformer
>>> column_trans = make_column_transformer(
...     (OneHotEncoder(), ['city']),
...     (CountVectorizer(), 'title'),
...     remainder=MinMaxScaler())
>>> column_trans
ColumnTransformer(remainder=MinMaxScaler(),
                  transformers=[('onehotencoder', OneHotEncoder(), ['city']),
                                ('countvectorizer', CountVectorizer(),
                                 'title')])

If ColumnTransformer is fitted with a dataframe and the dataframe only has string column names, then transforming a dataframe will use the column names to select the columns:

>>> ct = ColumnTransformer(
...          [("scale", StandardScaler(), ["expert_rating"])]).fit(X)
>>> X_new = pd.DataFrame({"expert_rating": [5, 6, 1],
...                       "ignored_new_col": [1.2, 0.3, -0.1]})
>>> ct.transform(X_new)
array([[ 0.9],
       [ 2.1],
       [-3.9]])

8.1.5. Visualizing Composite Estimators

Estimators are displayed with an HTML representation when shown in a jupyter notebook. This is useful to diagnose or visualize a Pipeline with many estimators. This visualization is activated by default:

>>> column_trans

It can be deactivated by setting the display option in set_config to ‘text’:

>>> from sklearn import set_config
>>> set_config(display='text')
>>> # displays text representation in a jupyter context
>>> column_trans

An example of the HTML output can be seen in the HTML representation of Pipeline section of Column Transformer with Mixed Types. As an alternative, the HTML can be written to a file using estimator_html_repr:

>>> from sklearn.utils import estimator_html_repr
>>> with open('my_estimator.html', 'w') as f:
...     f.write(estimator_html_repr(clf))

Examples

19.1. What Is Hyperparameter Optimization? 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.

19.1. What Is Hyperparameter Optimization?
Open the notebook in SageMaker Studio Lab

As we have seen in the previous chapters, deep neural networks come with a large number of parameters or weights that are learned during training. On top of these, every neural network has additional hyperparameters that need to be configured by the user. For example, to ensure that stochastic gradient descent converges to a local optimum of the training loss (see Section 12), we have to adjust the learning rate and batch size. To avoid overfitting on training datasets, we might have to set regularization parameters, such as weight decay (see Section 3.7) or dropout (see Section 5.6). We can define the capacity and inductive bias of the model by setting the number of layers and number of units or filters per layer (i.e., the effective number of weights).

Unfortunately, we cannot simply adjust these hyperparameters by minimizing the training loss, because this would lead to overfitting on the training data. For example, setting regularization parameters, such as dropout or weight decay to zero leads to a small training loss, but might hurt the generalization performance.

../_images/ml_workflow.svg

Fig. 19.1.1 Typical workflow in machine learning that consists of training the model multiple times with different hyperparameters.

Without a different form of automation, hyperparameters have to be set manually in a trial-and-error fashion, in what amounts to a time-consuming and difficult part of machine learning workflows. For example, consider training a ResNet (see Section 8.6) on CIFAR-10, which requires more than 2 hours on an Amazon Elastic Cloud Compute (EC2) g4dn.xlarge instance. Even just trying ten hyperparameter configurations in sequence, this would already take us roughly one day. To make matters worse, hyperparameters are usually not directly transferable across architectures and datasets (Bardenet et al., 2013, Feurer et al., 2022, Wistuba et al., 2018), and need to be re-optimized for every new task. Also, for most hyperparameters, there are no rule-of-thumbs, and expert knowledge is required to find sensible values.

Hyperparameter optimization (HPO) algorithms are designed to tackle this problem in a principled and automated fashion (Feurer and Hutter, 2018), by framing it as a global optimization problem. The default objective is the error on a hold-out validation dataset, but could in principle be any other business metric. It can be combined with or constrained by secondary objectives, such as training time, inference time, or model complexity.

Recently, hyperparameter optimization has been extended to neural architecture search (NAS) (Elsken et al., 2018, Wistuba et al., 2019), where the goal is to find entirely new neural network architectures. Compared to classical HPO, NAS is even more expensive in terms of computation and requires additional efforts to remain feasible in practice. Both, HPO and NAS can be considered as sub-fields of AutoML (Hutter et al., 2019), which aims to automate the entire ML pipeline.

In this section we will introduce HPO and show how we can automatically find the best hyperparameters of the logistic regression example introduced in Section 4.5.

19.1.1. The Optimization Problem

We will start with a simple toy problem: searching for the learning rate of the multi-class logistic regression model SoftmaxRegression from Section 4.5 to minimize the validation error on the Fashion MNIST dataset. While other hyperparameters like batch size or number of epochs are also worth tuning, we focus on learning rate alone for simplicity.

import numpy as np
import torch
from scipy import stats
from torch import nn
from d2l import torch as d2l

Before we can run HPO, we first need to define two ingredients: the objective function and the configuration space.

19.1.1.1. The Objective Function

The performance of a learning algorithm can be seen as a function \(f: \mathcal{X} \rightarrow \mathbb{R}\) that maps from the hyperparameter space \(\mathbf{x} \in \mathcal{X}\) to the validation loss. For every evaluation of \(f(\mathbf{x})\), we have to train and validate our machine learning model, which can be time and compute intensive in the case of deep neural networks trained on large datasets. Given our criterion \(f(\mathbf{x})\) our goal is to find \(\mathbf{x}_{\star} \in \mathrm{argmin}_{\mathbf{x} \in \mathcal{X}} f(\mathbf{x})\).

There is no simple way to compute gradients of \(f\) with respect to \(\mathbf{x}\), because it would require to propagate the gradient through the entire training process. While there is recent work (Franceschi et al., 2017, Maclaurin et al., 2015) to drive HPO by approximate “hypergradients”, none of the existing approaches are competitive with the state-of-the-art yet, and we will not discuss them here. Furthermore, the computational burden of evaluating \(f\) requires HPO algorithms to approach the global optimum with as few samples as possible.

The training of neural networks is stochastic (e.g., weights are randomly initialized, mini-batches are randomly sampled), so that our observations will be noisy: \(y \sim f(\mathbf{x}) + \epsilon\), where we usually assume that the \(\epsilon \sim N(0, \sigma)\) observation noise is Gaussian distributed.

Faced with all these challenges, we usually try to identify a small set of well performing hyperparameter configurations quickly, instead of hitting the global optima exactly. However, due to large computational demands of most neural networks models, even this can take days or weeks of compute. We will explore in Section 19.4 how we can speed-up the optimization process by either distributing the search or using cheaper-to-evaluate approximations of the objective function.

We begin with a method for computing the validation error of a model.

class HPOTrainer(d2l.Trainer):  #@save
    def validation_error(self):
        self.model.eval()
        accuracy = 0
        val_batch_idx = 0
        for batch in self.val_dataloader:
            with torch.no_grad():
                x, y = self.prepare_batch(batch)
                y_hat = self.model(x)
                accuracy += self.model.accuracy(y_hat, y)
            val_batch_idx += 1
        return 1 -  accuracy / val_batch_idx

We optimize validation error with respect to the hyperparameter configuration config, consisting of the learning_rate. For each evaluation, we train our model for max_epochs epochs, then compute and return its validation error:

def hpo_objective_softmax_classification(config, max_epochs=8):
    learning_rate = config["learning_rate"]
    trainer = d2l.HPOTrainer(max_epochs=max_epochs)
    data = d2l.FashionMNIST(batch_size=16)
    model = d2l.SoftmaxRegression(num_outputs=10, lr=learning_rate)
    trainer.fit(model=model, data=data)
    return trainer.validation_error().detach().numpy()

19.1.1.2. The Configuration Space

Along with the objective function \(f(\mathbf{x})\), we also need to define the feasible set \(\mathbf{x} \in \mathcal{X}\) to optimize over, known as configuration space or search space. For our logistic regression example, we will use:

config_space = {"learning_rate": stats.loguniform(1e-4, 1)}

Here we use the use the loguniform object from SciPy, which represents a uniform distribution between -4 and -1 in the logarithmic space. This object allows us to sample random variables from this distribution.

Each hyperparameter has a data type, such as float for learning_rate, as well as a closed bounded range (i.e., lower and upper bounds). We usually assign a prior distribution (e.g, uniform or log-uniform) to each hyperparameter to sample from. Some positive parameters, such as learning_rate, are best represented on a logarithmic scale as optimal values can differ by several orders of magnitude, while others, such as momentum, come with linear scale.

Below we show a simple example of a configuration space consisting of typical hyperparameters of a multi-layer perceptron including their type and standard ranges.

: Example configuration space of multi-layer perceptron

Table 19.1.1 label:tab_example_configspace

Name

Type

Hyperparameter Ranges

log-scale

learning rate

float

:math:` [10^{-6},10^{-1}]`

yes

batch size

integer

\([8,256]\)

yes

momentum

float

\([0,0.99]\)

no

activation function

categorical

:mat h:{textrm{tanh} , textrm{relu}}

number of units

integer

\([32, 1024]\)

yes

number of layers

integer

\([1, 6]\)

no

In general, the structure of the configuration space \(\mathcal{X}\) can be complex and it can be quite different from \(\mathbb{R}^d\). In practice, some hyperparameters may depend on the value of others. For example, assume we try to tune the number of layers for a multi-layer perceptron, and for each layer the number of units. The number of units of the \(l\textrm{-th}\) layer is relevant only if the network has at least \(l+1\) layers. These advanced HPO problems are beyond the scope of this chapter. We refer the interested reader to (Baptista and Poloczek, 2018, Hutter et al., 2011, Jenatton et al., 2017).

The configuration space plays an important role for hyperparameter optimization, since no algorithms can find something that is not included in the configuration space. On the other hand, if the ranges are too large, the computation budget to find well performing configurations might become infeasible.

19.1.3. Summary

In this section we introduced hyperparameter optimization (HPO) and how we can phrase it as a global optimization by defining a configuration space and an objective function. We also implemented our first HPO algorithm, random search, and applied it on a simple softmax classification problem.

While random search is very simple, it is the better alternative to grid search, which simply evaluates a fixed set of hyperparameters. Random search somewhat mitigates the curse of dimensionality (Bellman, 1966), and can be far more efficient than grid search if the criterion most strongly depends on a small subset of the hyperparameters.

19.1.4. Exercises

  1. In this chapter, we optimize the validation error of a model after training on a disjoint training set. For simplicity, our code uses Trainer.val_dataloader, which maps to a loader around FashionMNIST.val.

    1. Convince yourself (by looking at the code) that this means we use the original FashionMNIST training set (60000 examples) for training, and the original test set (10000 examples) for validation.

    2. Why could this practice be problematic? Hint: Re-read Section 3.6, especially about model selection.

    3. What should we have done instead?

  2. We stated above that hyperparameter optimization by gradient descent is very hard to do. Consider a small problem, such as training a two-layer perceptron on the FashionMNIST dataset (Section 5.2) with a batch size of 256. We would like to tune the learning rate of SGD in order to minimize a validation metric after one epoch of training.

    1. Why cannot we use validation error for this purpose? What metric on the validation set would you use?

    2. Sketch (roughly) the computational graph of the validation metric after training for one epoch. You may assume that initial weights and hyperparameters (such as learning rate) are input nodes to this graph. Hint: Re-read about computational graphs in Section 5.3.

    3. Give a rough estimate of the number of floating point values you need to store during a forward pass on this graph. Hint: FashionMNIST has 60000 cases. Assume the required memory is dominated by the activations after each layer, and look up the layer widths in Section 5.2.

    4. Apart from the sheer amount of compute and storage required, what other issues would gradient-based hyperparameter optimization run into? Hint: Re-read about vanishing and exploding gradients in Section 5.4.

    5. Advanced: Read (Maclaurin et al., 2015) for an elegant (yet still somewhat unpractical) approach to gradient-based HPO.

  3. Grid search is another HPO baseline, where we define an equi-spaced grid for each hyperparameter, then iterate over the (combinatorial) Cartesian product in order to suggest configurations.

    1. We stated above that random search can be much more efficient than grid search for HPO on a sizable number of hyperparameters, if the criterion most strongly depends on a small subset of the hyperparameters. Why is this? Hint: Read (Bergstra et al., 2011).

Discussions

10.2. Computational Performance

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.

10.2. Computational Performance

For some applications the performance (mainly latency and throughput at prediction time) of estimators is crucial. It may also be of interest to consider the training throughput but this is often less important in a production setup (where it often takes place offline).

We will review here the orders of magnitude you can expect from a number of scikit-learn estimators in different contexts and provide some tips and tricks for overcoming performance bottlenecks.

Prediction latency is measured as the elapsed time necessary to make a prediction (e.g. in microseconds). Latency is often viewed as a distribution and operations engineers often focus on the latency at a given percentile of this distribution (e.g. the 90th percentile).

Prediction throughput is defined as the number of predictions the software can deliver in a given amount of time (e.g. in predictions per second).

An important aspect of performance optimization is also that it can hurt prediction accuracy. Indeed, simpler models (e.g. linear instead of non-linear, or with fewer parameters) often run faster but are not always able to take into account the same exact properties of the data as more complex ones.

10.2.1. Prediction Latency

One of the most straightforward concerns one may have when using/choosing a machine learning toolkit is the latency at which predictions can be made in a production environment.

The main factors that influence the prediction latency are

  1. Number of features

  2. Input data representation and sparsity

  3. Model complexity

  4. Feature extraction

A last major parameter is also the possibility to do predictions in bulk or one-at-a-time mode.

10.2.1.1. Bulk versus Atomic mode

In general doing predictions in bulk (many instances at the same time) is more efficient for a number of reasons (branching predictability, CPU cache, linear algebra libraries optimizations etc.). Here we see on a setting with few features that independently of estimator choice the bulk mode is always faster, and for some of them by 1 to 2 orders of magnitude:

atomic_prediction_latency

bulk_prediction_latency

To benchmark different estimators for your case you can simply change the n_features parameter in this example: Prediction Latency. This should give you an estimate of the order of magnitude of the prediction latency.

10.2.1.2. Configuring Scikit-learn for reduced validation overhead

Scikit-learn does some validation on data that increases the overhead per call to predict and similar functions. In particular, checking that features are finite (not NaN or infinite) involves a full pass over the data. If you ensure that your data is acceptable, you may suppress checking for finiteness by setting SKLEARN_ASSUME_FINITE before importing scikit-learn, or configure it in Python with set_config. For more control than these global settings, a config_context allows you to set this configuration within a specified context:

>>> import sklearn
>>> with sklearn.config_context(assume_finite=True):
...     pass  # do learning/prediction here with reduced validation

Note that this will affect all uses of assert_all_finite within the context.

10.2.1.3. Influence of the Number of Features

Obviously when the number of features increases so does the memory consumption of each example. Indeed, for a matrix of \(M\) instances with \(N\) features, the space complexity is in \(O(NM)\). From a computing perspective it also means that the number of basic operations (e.g., multiplications for vector-matrix products in linear models) increases too. Here is a graph of the evolution of the prediction latency with the number of features:

influence_of_n_features_on_latency

Overall you can expect the prediction time to increase at least linearly with the number of features (non-linear cases can happen depending on the global memory footprint and estimator).

10.2.1.4. Influence of the Input Data Representation

Scipy provides sparse matrix data structures which are optimized for storing sparse data. The main feature of sparse formats is that you don’t store zeros so if your data is sparse then you use much less memory. A non-zero value in a sparse (CSR or CSC) representation will only take on average one 32bit integer position + the 64 bit floating point value + an additional 32bit per row or column in the matrix. Using sparse input on a dense (or sparse) linear model can speedup prediction by quite a bit as only the non zero valued features impact the dot product and thus the model predictions. Hence if you have 100 non zeros in 1e6 dimensional space, you only need 100 multiply and add operation instead of 1e6.

Calculation over a dense representation, however, may leverage highly optimized vector operations and multithreading in BLAS, and tends to result in fewer CPU cache misses. So the sparsity should typically be quite high (10% non-zeros max, to be checked depending on the hardware) for the sparse input representation to be faster than the dense input representation on a machine with many CPUs and an optimized BLAS implementation.

Here is sample code to test the sparsity of your input:

def sparsity_ratio(X):
    return 1.0 - np.count_nonzero(X) / float(X.shape[0] * X.shape[1])
print("input sparsity ratio:", sparsity_ratio(X))

As a rule of thumb you can consider that if the sparsity ratio is greater than 90% you can probably benefit from sparse formats. Check Scipy’s sparse matrix formats documentation for more information on how to build (or convert your data to) sparse matrix formats. Most of the time the CSR and CSC formats work best.

10.2.1.5. Influence of the Model Complexity

Generally speaking, when model complexity increases, predictive power and latency are supposed to increase. Increasing predictive power is usually interesting, but for many applications we would better not increase prediction latency too much. We will now review this idea for different families of supervised models.

For sklearn.linear_model (e.g. Lasso, ElasticNet, SGDClassifier/Regressor, Ridge & RidgeClassifier, LinearSVC, LogisticRegression…) the decision function that is applied at prediction time is the same (a dot product), so latency should be equivalent.

Here is an example using SGDClassifier with the elasticnet penalty. The regularization strength is globally controlled by the alpha parameter. With a sufficiently high alpha, one can then increase the l1_ratio parameter of elasticnet to enforce various levels of sparsity in the model coefficients. Higher sparsity here is interpreted as less model complexity as we need fewer coefficients to describe it fully. Of course sparsity influences in turn the prediction time as the sparse dot-product takes time roughly proportional to the number of non-zero coefficients.

en_model_complexity

For the sklearn.svm family of algorithms with a non-linear kernel, the latency is tied to the number of support vectors (the fewer the faster). Latency and throughput should (asymptotically) grow linearly with the number of support vectors in an SVC or SVR model. The kernel will also influence the latency as it is used to compute the projection of the input vector once per support vector. In the following graph the nu parameter of NuSVR was used to influence the number of support vectors.

nusvr_model_complexity

For sklearn.ensemble of trees (e.g. RandomForest, GBT, ExtraTrees, etc.) the number of trees and their depth play the most important role. Latency and throughput should scale linearly with the number of trees. In this case we used directly the n_estimators parameter of GradientBoostingRegressor.

gbt_model_complexity

In any case be warned that decreasing model complexity can hurt accuracy as mentioned above. For instance a non-linearly separable problem can be handled with a speedy linear model but prediction power will very likely suffer in the process.

10.2.1.6. Feature Extraction Latency

Most scikit-learn models are usually pretty fast as they are implemented either with compiled Cython extensions or optimized computing libraries. On the other hand, in many real world applications the feature extraction process (i.e. turning raw data like database rows or network packets into numpy arrays) governs the overall prediction time. For example on the Reuters text classification task the whole preparation (reading and parsing SGML files, tokenizing the text and hashing it into a common vector space) is taking 100 to 500 times more time than the actual prediction code, depending on the chosen model.

prediction_time

In many cases it is thus recommended to carefully time and profile your feature extraction code as it may be a good place to start optimizing when your overall latency is too slow for your application.

10.2.2. Prediction Throughput

Another important metric to care about when sizing production systems is the throughput i.e. the number of predictions you can make in a given amount of time. Here is a benchmark from the Prediction Latency example that measures this quantity for a number of estimators on synthetic data:

throughput_benchmark

These throughputs are achieved on a single process. An obvious way to increase the throughput of your application is to spawn additional instances (usually processes in Python because of the GIL) that share the same model. One might also add machines to spread the load. A detailed explanation on how to achieve this is beyond the scope of this documentation though.

10.2.3. Tips and Tricks

10.2.3.1. Linear algebra libraries

As scikit-learn relies heavily on Numpy/Scipy and linear algebra in general it makes sense to take explicit care of the versions of these libraries. Basically, you ought to make sure that Numpy is built using an optimized BLAS / LAPACK library.

Not all models benefit from optimized BLAS and Lapack implementations. For instance models based on (randomized) decision trees typically do not rely on BLAS calls in their inner loops, nor do kernel SVMs (SVC, SVR, NuSVC, NuSVR). On the other hand a linear model implemented with a BLAS DGEMM call (via numpy.dot) will typically benefit hugely from a tuned BLAS implementation and lead to orders of magnitude speedup over a non-optimized BLAS.

You can display the BLAS / LAPACK implementation used by your NumPy / SciPy / scikit-learn install with the following command:

python -c "import sklearn; sklearn.show_versions()"

Optimized BLAS / LAPACK implementations include:

  • OpenBLAS (e.g. default in Numpy and SciPy PyPI wheels)

  • MKL

  • Apple Accelerate and vecLib frameworks (OSX only)

More information can be found on the NumPy install page and in this blog post from Daniel Nouri which has some nice step by step install instructions for Debian / Ubuntu.

10.2.3.2. Limiting Working Memory

Some calculations when implemented using standard numpy vectorized operations involve using a large amount of temporary memory. This may potentially exhaust system memory. Where computations can be performed in fixed-memory chunks, we attempt to do so, and allow the user to hint at the maximum size of this working memory (defaulting to 1GB) using set_config or config_context. See SKLEARN_WORKING_MEMORY which can be used to change the global default.

The following suggests to limit temporary working memory to 128 MiB:

>>> import sklearn
>>> with sklearn.config_context(working_memory=128):
...     pass  # do chunked work here

An example of a chunked operation adhering to this setting is pairwise_distances_chunked, which facilitates computing row-wise reductions of a pairwise distance matrix.

10.2.3.3. Model Compression

Model compression in scikit-learn only concerns linear models for the moment. In this context it means that we want to control the model sparsity (i.e. the number of non-zero coordinates in the model vectors). It is generally a good idea to combine model sparsity with sparse input data representation.

Here is sample code that illustrates the use of the sparsify() method:

clf = SGDRegressor(penalty='elasticnet', l1_ratio=0.25)
clf.fit(X_train, y_train).sparsify()
clf.predict(X_test)

In this example we prefer the elasticnet penalty as it is often a good compromise between model compactness and prediction power. One can also further tune the l1_ratio parameter (in combination with the regularization strength alpha) to control this tradeoff.

A typical benchmark on synthetic data yields a >30% decrease in latency when both the model and input are sparse (with 0.000024 and 0.027400 non-zero coefficients ratio respectively). Your mileage may vary depending on the sparsity and size of your data and model. Furthermore, sparsifying can be very useful to reduce the memory usage of predictive models deployed on production servers.

10.2.3.4. Model Reshaping

Model reshaping consists in selecting only a portion of the available features to fit a model. In other words, if a model discards features during the learning phase we can then strip those from the input. This has several benefits. Firstly it reduces memory (and therefore time) overhead of the model itself. It also allows to discard explicit feature selection components in a pipeline once we know which features to keep from a previous run. Finally, it can help reduce processing time and I/O usage upstream in the data access and feature extraction layers by not collecting and building features that are discarded by the model. For instance if the raw data come from a database, it is possible to write simpler and faster queries or reduce I/O usage by making the queries return lighter records. At the moment, reshaping needs to be performed manually in scikit-learn. In the case of sparse input (particularly in CSR format), it is generally sufficient to not generate the relevant features, leaving their columns empty.

LLM05:2025 Improper Output Handling

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.

LLM05:2025 Improper Output Handling

Improper Output Handling refers specifically to insufficient validation, sanitization, and handling of the outputs generated by large language models before they are passed downstream to other components and systems. Since LLM-generated content can be controlled by prompt input, this behavior is similar to providing users indirect access to additional functionality. Improper Output Handling differs from Overreliance in that it deals with LLM-generated outputs before they are passed downstream whereas Overreliance focuses on broader concerns around overdependence on the accuracy and appropriateness of LLM outputs. Successful exploitation of an Improper Output Handling vulnerability can result in XSS and CSRF in web browsers as well as SSRF, privilege escalation, or remote code execution on backend systems. The following conditions can increase the impact of this vulnerability:

  • The application grants the LLM privileges beyond what is intended for end users, enabling escalation of privileges or remote code execution.
  • The application is vulnerable to indirect prompt injection attacks, which could allow an attacker to gain privileged access to a target user’s environment.
  • 3rd party extensions do not adequately validate inputs.
  • Lack of proper output encoding for different contexts (e.g., HTML, JavaScript, SQL)
  • Insufficient monitoring and logging of LLM outputs
  • Absence of rate limiting or anomaly detection for LLM usage
  1. LLM output is entered directly into a system shell or similar function such as exec or eval, resulting in remote code execution.
  2. JavaScript or Markdown is generated by the LLM and returned to a user. The code is then interpreted by the browser, resulting in XSS.
  3. LLM-generated SQL queries are executed without proper parameterization, leading to SQL injection.
  4. LLM output is used to construct file paths without proper sanitization, potentially resulting in path traversal vulnerabilities.
  5. LLM-generated content is used in email templates without proper escaping, potentially leading to phishing attacks.
  1. Treat the model as any other user, adopting a zero-trust approach, and apply proper input validation on responses coming from the model to backend functions.
  2. Follow the OWASP ASVS (Application Security Verification Standard) guidelines to ensure effective input validation and sanitization.
  3. Encode model output back to users to mitigate undesired code execution by JavaScript or Markdown. OWASP ASVS provides detailed guidance on output encoding.
  4. Implement context-aware output encoding based on where the LLM output will be used (e.g., HTML encoding for web content, SQL escaping for database queries).
  5. Use parameterized queries or prepared statements for all database operations involving LLM output.
  6. Employ strict Content Security Policies (CSP) to mitigate the risk of XSS attacks from LLM-generated content.
  7. Implement robust logging and monitoring systems to detect unusual patterns in LLM outputs that might indicate exploitation attempts.

An application utilizes an LLM extension to generate responses for a chatbot feature. The extension also offers a number of administrative functions accessible to another privileged LLM. The general purpose LLM directly passes its response, without proper output validation, to the extension causing the extension to shut down for maintenance.

A user utilizes a website summarizer tool powered by an LLM to generate a concise summary of an article. The website includes a prompt injection instructing the LLM to capture sensitive content from either the website or from the user’s conversation. From there the LLM can encode the sensitive data and send it, without any output validation or filtering, to an attacker-controlled server.

An LLM allows users to craft SQL queries for a backend database through a chat-like feature. A user requests a query to delete all database tables. If the crafted query from the LLM is not scrutinized, then all database tables will be deleted.

A web app uses an LLM to generate content from user text prompts without output sanitization. An attacker could submit a crafted prompt causing the LLM to return an unsanitized JavaScript payload, leading to XSS when rendered on a victim’s browser. Insufficient validation of prompts enabled this attack.

An LLM is used to generate dynamic email templates for a marketing campaign. An attacker manipulates the LLM to include malicious JavaScript within the email content. If the application doesn’t properly sanitize the LLM output, this could lead to XSS attacks on recipients who view the email in vulnerable email clients.

An LLM is used to generate code from natural language inputs in a software company, aiming to streamline development tasks. While efficient, this approach risks exposing sensitive information, creating insecure data handling methods, or introducing vulnerabilities like SQL injection. The AI may also hallucinate non-existent software packages, potentially leading developers to download malware-infected resources. Thorough code review and verification of suggested packages are crucial to prevent security breaches, unauthorized access, and system compromises.

  1. Proof Pudding (CVE-2019-20634) AVID (moohax & monoxgas)
  2. Arbitrary Code Execution: Snyk Security Blog
  3. ChatGPT Plugin Exploit Explained: From Prompt Injection to Accessing Private Data: Embrace The Red
  4. New prompt injection attack on ChatGPT web version. Markdown images can steal your chat data.: System Weakness
  5. Don’t blindly trust LLM responses. Threats to chatbots: Embrace The Red
  6. Threat Modeling LLM Applications: AI Village
  7. OWASP ASVS – 5 Validation, Sanitization and Encoding: OWASP AASVS
  8. AI hallucinates software packages and devs download them – even if potentially poisoned with malware Theregiste

    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 8: User authentication and permissions

    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 8: User authentication and permissions

    In this tutorial, we'll show you how to allow users to log into your site with their own accounts, and how to control what they can do and see based on whether or not they are logged in and their permissions. As part of this demonstration, we'll extend the LocalLibrary website, adding login and logout pages, and user- and staff-specific pages for viewing books that have been borrowed.

    Prerequisites: Complete all previous tutorial topics, up to and including Django Tutorial Part 7: Sessions framework.
    Objective: To understand how to set up and use user authentication and permissions.

    Overview

    Django provides an authentication and authorization ("permission") system, built on top of the session framework discussed in the previous tutorial, that allows you to verify user credentials and define what actions each user is allowed to perform. The framework includes built-in models for Users and Groups (a generic way of applying permissions to more than one user at a time), permissions/flags that designate whether a user may perform a task, forms and views for logging in users, and view tools for restricting content.

    Note: According to Django the authentication system aims to be very generic, and so does not provide some features provided in other web authentication systems. Solutions for some common problems are available as third-party packages. For example, throttling of login attempts and authentication against third parties (e.g., OAuth).

    In this tutorial, we'll show you how to enable user authentication in the LocalLibrary website, create your own login and logout pages, add permissions to your models, and control access to pages. We'll use the authentication/permissions to display lists of books that have been borrowed for both users and librarians.

    The authentication system is very flexible, and you can build up your URLs, forms, views, and templates from scratch if you like, just calling the provided API to log in the user. However, in this article, we're going to use Django's "stock" authentication views and forms for our login and logout pages. We'll still need to create some templates, but that's pretty easy.

    We'll also show you how to create permissions, and check on login status and permissions in both views and templates.

    Enabling authentication

    The authentication was enabled automatically when we created the skeleton website (in tutorial 2) so you don't need to do anything more at this point.

    Note: The necessary configuration was all done for us when we created the app using the django-admin startproject command. The database tables for users and model permissions were created when we first called python manage.py migrate.

    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.auth',  # Core authentication framework and its default models.
        'django.contrib.contenttypes',  # Django content type system (allows permissions to be associated with models).
        # …
    
    MIDDLEWARE = [
        # …
        'django.contrib.sessions.middleware.SessionMiddleware',  # Manages sessions across requests
        # …
        'django.contrib.auth.middleware.AuthenticationMiddleware',  # Associates users with requests using sessions.
        # …
    

    Creating users and groups

    You already created your first user when we looked at the Django admin site in tutorial 4 (this was a superuser, created with the command python manage.py createsuperuser). Our superuser is already authenticated and has all permissions, so we'll need to create a test user to represent a normal site user. We'll be using the admin site to create our locallibrary groups and website logins, as it is one of the quickest ways to do so.

    Note: You can also create users programmatically as shown below. You would have to do this, for example, if developing an interface to allow "ordinary" users to create their own logins (you shouldn't give most users access to the admin site).

    python
    from django.contrib.auth.models import User
    
    # Create user and save to the database
    user = User.objects.create_user('myusername', 'myemail@crazymail.com', 'mypassword')
    
    # Update fields and then save again
    user.first_name = 'Tyrone'
    user.last_name = 'Citizen'
    user.save()
    

    Note however that it is highly recommended to set up a custom user model when starting a project, as you'll be able to easily customize it in the future if the need arises. If using a custom user model the code to create the same user would look like this:

    python
    # Get current user model from settings
    from django.contrib.auth import get_user_model
    User = get_user_model()
    
    # Create user from model and save to the database
    user = User.objects.create_user('myusername', 'myemail@crazymail.com', 'mypassword')
    
    # Update fields and then save again
    user.first_name = 'Tyrone'
    user.last_name = 'Citizen'
    user.save()
    

    For more information, see Using a custom user model when starting a project (Django docs).

    Below we'll first create a group and then a user. Even though we don't have any permissions to add for our library members yet, if we need to later, it will be much easier to add them once to the group than individually to each member.

    Start the development server and navigate to the admin site in your local web browser (http://127.0.0.1:8000/admin/). Log into the site using the credentials for your superuser account. The top level of the Admin site displays all of your models, sorted by "Django application". From the Authentication and Authorization section, you can click the Users or Groups links to see their existing records.

    Admin site - add groups or users

    First let's create a new group for our library members.

    1. Click the Add button (next to Group) to create a new Group; enter the Name "Library Members" for the group. Admin site - add group
    2. We don't need any permissions for the group, so just press SAVE (you will be taken to a list of groups).

    Now let's create a user:

    1. Navigate back to the home page of the admin site

    2. Click the Add button next to Users to open the Add user dialog box. Admin site - add user pt1

    3. Enter an appropriate Username and Password/Password confirmation for your test user

    4. Press SAVE to create the user.

      The admin site will create the new user and immediately take you to a Change user screen where you can change your username and add information for the User model's optional fields. These fields include the first name, last name, email address, and the user's status and permissions (only the Active flag should be set). Further down you can specify the user's groups and permissions, and see important dates related to the user (e.g., their join date and last login date). Admin site - add user pt2

    5. In the Groups section, select Library Member group from the list of Available groups, and then press the right-arrow between the boxes to move it into the Chosen groups box. Admin site - add user to group

    6. We don't need to do anything else here, so just select SAVE again, to go to the list of users.

    That's it! Now you have a "normal library member" account that you will be able to use for testing (once we've implemented the pages to enable them to log in).

    Note: You should try creating another library member user. Also, create a group for Librarians, and add a user to that too!

    Setting up your authentication views

    Django provides almost everything you need to create authentication pages to handle login, log out, and password management "out of the box". This includes a URL mapper, views and forms, but it does not include the templates — we have to create our own!

    In this section, we show how to integrate the default system into the LocalLibrary website and create the templates.

    Note: Django does not include a built-in authentication view for initial user registration ("signup"). You can create one yourself if needed, but for this tutorial we assume that only librarians are allowed to register users, and that they would do so using the Django admin interface.

    Note: You don't have to use any of this code, but it is likely that you'll want to because it makes things a lot easier. You'll almost certainly need to change the form handling code if you change your user model, but even so, you would still be able to use the stock view functions.

    Note: In this case, we could reasonably put the authentication pages, including the URLs and templates, inside our catalog application. However, if we had multiple applications it would be better to separate out this shared login behavior and have it available across the whole site, so that is what we've shown here!

    Project URLs

    Add the following to the bottom of the project urls.py file (django-locallibrary-tutorial/locallibrary/urls.py) file:

    python
    # Add Django site authentication urls (for login, logout, password management)
    
    urlpatterns += [
        path('accounts/', include('django.contrib.auth.urls')),
    ]
    

    Navigate to the http://127.0.0.1:8000/accounts/ URL (note the trailing forward slash!). Django will show an error that it could not find a mapping for this URL, and list all the URLs that it tried. From this you can see the URLs that will work once we have created templates.

    Note: Adding the accounts/ path as shown above adds the following URLs, along with names (given in square brackets) that can be used to reverse the URL mappings. You don't have to implement anything else — the above URL mapping automatically maps the below mentioned URLs.

    python
    accounts/ login/ [name='login']
    accounts/ logout/ [name='logout']
    accounts/ password_change/ [name='password_change']
    accounts/ password_change/done/ [name='password_change_done']
    accounts/ password_reset/ [name='password_reset']
    accounts/ password_reset/done/ [name='password_reset_done']
    accounts/ reset/<uidb64>/<token>/ [name='password_reset_confirm']
    accounts/ reset/done/ [name='password_reset_complete']
    

    Now try to navigate to the login URL (http://127.0.0.1:8000/accounts/login/). This will fail again, but with an error that tells you that we're missing the required template (registration/login.html) on the template search path. You'll see the following lines listed in the yellow section at the top:

    python
    Exception Type:    TemplateDoesNotExist
    Exception Value:    registration/login.html
    

    The next step is to create a directory for the templates named "registration" and then add the login.html file.

    Template directory

    The URLs (and implicitly, views) that we just added expect to find their associated templates in a directory /registration/ somewhere in the templates search path.

    For this site, we'll put our HTML pages in the templates/registration/ directory. This directory should be in your project root directory, that is, the same directory as the catalog and locallibrary folders. Please create these folders now.

    Note: Your folder structure should now look like the below:

    django-locallibrary-tutorial/   # Django top level project folder
      catalog/
      locallibrary/
      templates/
        registration/
    

    To make the templates directory visible to the template loader we need to add it in the template search path. Open the project settings (/django-locallibrary-tutorial/locallibrary/settings.py).

    Then import the os module (add the following line near the top of the file if it isn't already present).

    python
    import os # needed by code below
    

    Update the TEMPLATES section's 'DIRS' line as shown:

    python
        # …
        TEMPLATES = [
          {
           # …
           'DIRS': [os.path.join(BASE_DIR, 'templates')],
           'APP_DIRS': True,
           # …
    

    Login template

    Warning: The authentication templates provided in this article are a very basic/slightly modified version of the Django demonstration login templates. You may need to customize them for your own use!

    Create a new HTML file called /django-locallibrary-tutorial/templates/registration/login.html and give it the following contents:

    django
    {% extends "base_generic.html" %}
    
    {% block content %}
    
      {% if form.errors %}
        <p>Your username and password didn't match. Please try again.</p>
      {% endif %}
    
      {% if next %}
        {% if user.is_authenticated %}
          <p>Your account doesn't have access to this page. To proceed,
          please log in with an account that has access.</p>
        {% else %}
          <p>Please log in to see this page.</p>
        {% endif %}
      {% endif %}
    
      <form method="post" action="{% url 'login' %}">
        {% csrf_token %}
        <table>
          <tr>
            <td>{{ form.username.label_tag }}</td>
            <td>{{ form.username }}</td>
          </tr>
          <tr>
            <td>{{ form.password.label_tag }}</td>
            <td>{{ form.password }}</td>
          </tr>
        </table>
        <input type="submit" value="login">
        <input type="hidden" name="next" value="{{ next }}">
      </form>
    
      {# Assumes you set up the password_reset view in your URLConf #}
      <p><a href="{% url 'password_reset' %}">Lost password?</a></p>
    
    {% endblock %}
    

    This template shares some similarities with the ones we've seen before — it extends our base template and overrides the content block. The rest of the code is fairly standard form handling code, which we will discuss in a later tutorial. All you need to know for now is that this will display a form in which you can enter your username and password, and that if you enter invalid values you will be prompted to enter correct values when the page refreshes.

    Navigate back to the login page (http://127.0.0.1:8000/accounts/login/) once you've saved your template, and you should see something like this:

    Library login page v1

    If you log in using valid credentials, you'll be redirected to another page (by default this will be http://127.0.0.1:8000/accounts/profile/). The problem is that, by default, Django expects that upon logging in you will want to be taken to a profile page, which may or may not be the case. As you haven't defined this page yet, you'll get another error!

    Open the project settings (/django-locallibrary-tutorial/locallibrary/settings.py) and add the text below to the bottom. Now when you log in you should be redirected to the site homepage by default.

    python
    # Redirect to home URL after login (Default redirects to /accounts/profile/)
    LOGIN_REDIRECT_URL = '/'
    

    Logout template

    If you navigate to the logout URL (http://127.0.0.1:8000/accounts/logout/) then you'll get an error because Django 5 does not allow logout using GET, only POST. We'll add a form you can use to log out in a minute, but first we'll create the page that users are taken to after logging out.

    Create and open /django-locallibrary-tutorial/templates/registration/logged_out.html. Copy in the text below:

    django
    {% extends "base_generic.html" %}
    
    {% block content %}
      <p>Logged out!</p>
      <a href="{% url 'login'%}">Click here to log in again.</a>
    {% endblock %}
    

    This template is very simple. It just displays a message informing you that you have been logged out, and provides a link that you can press to go back to the login screen. The screen renders like this (after logout):

    Library logout page v1

    Password reset templates

    The default password reset system uses email to send the user a reset link. You need to create forms to get the user's email address, send the email, allow them to enter a new password, and to note when the whole process is complete.

    The following templates can be used as a starting point.

    Password reset form

    This is the form used to get the user's email address (for sending the password reset email). Create /django-locallibrary-tutorial/templates/registration/password_reset_form.html, and give it the following contents:

    django
    {% extends "base_generic.html" %}
    
    {% block content %}
      <form action="" method="post">
      {% csrf_token %}
      {% if form.email.errors %}
        {{ form.email.errors }}
      {% endif %}
          <p>{{ form.email }}</p>
        <input type="submit" class="btn btn-default btn-lg" value="Reset password">
      </form>
    {% endblock %}
    

    Password reset done

    This form is displayed after your email address has been collected. Create /django-locallibrary-tutorial/templates/registration/password_reset_done.html, and give it the following contents:

    django
    {% extends "base_generic.html" %}
    
    {% block content %}
      <p>We've emailed you instructions for setting your password. If they haven't arrived in a few minutes, check your spam folder.</p>
    {% endblock %}
    

    Password reset email

    This template provides the text of the HTML email containing the reset link that we will send to users. Create /django-locallibrary-tutorial/templates/registration/password_reset_email.html, and give it the following contents:

    django
    Someone asked for password reset for email {{ email }}. Follow the link below:
    {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
    

    Password reset confirm

    This page is where you enter your new password after clicking the link in the password reset email. Create /django-locallibrary-tutorial/templates/registration/password_reset_confirm.html, and give it the following contents:

    django
    {% extends "base_generic.html" %}
    
    {% block content %}
        {% if validlink %}
            <p>Please enter (and confirm) your new password.</p>
            <form action="" method="post">
            {% csrf_token %}
                <table>
                    <tr>
                        <td>{{ form.new_password1.errors }}
                            <label for="id_new_password1">New password:</label></td>
                        <td>{{ form.new_password1 }}</td>
                    </tr>
                    <tr>
                        <td>{{ form.new_password2.errors }}
                            <label for="id_new_password2">Confirm password:</label></td>
                        <td>{{ form.new_password2 }}</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td><input type="submit" value="Change my password"></td>
                    </tr>
                </table>
            </form>
        {% else %}
            <h1>Password reset failed</h1>
            <p>The password reset link was invalid, possibly because it has already been used. Please request a new password reset.</p>
        {% endif %}
    {% endblock %}
    

    Password reset complete

    This is the last password-reset template, which is displayed to notify you when the password reset has succeeded. Create /django-locallibrary-tutorial/templates/registration/password_reset_complete.html, and give it the following contents:

    django
    {% extends "base_generic.html" %}
    
    {% block content %}
      <h1>The password has been changed!</h1>
      <p><a href="{% url 'login' %}">log in again?</a></p>
    {% endblock %}
    

    Testing the new authentication pages

    Now that you've added the URL configuration and created all these templates, the authentication pages (other than logout) should now just work!

    You can test the new authentication pages by first attempting to log into your superuser account using the URL http://127.0.0.1:8000/accounts/login/. You'll be able to test the password reset functionality from the link in the login page. Be aware that Django will only send reset emails to addresses (users) that are already stored in its database!

    Note that you won't be able to test account logout yet, because logout requests must be sent as a POST rather than a GET request.

    Note: The password reset system requires that your website supports email, which is beyond the scope of this article, so this part won't work yet. To allow testing, put the following line at the end of your settings.py file. This logs any emails sent to the console (so you can copy the password reset link from the console).

    python
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
    

    For more information, see Sending email (Django docs).

    Testing against authenticated users

    This section looks at what we can do to selectively control content the user sees based on whether they are logged in or not.

    Testing in templates

    You can get information about the currently logged in user in templates with the {{ user }} template variable (this is added to the template context by default when you set up the project as we did in our skeleton).

    Typically you will first test against the {{ user.is_authenticated }} template variable to determine whether the user is eligible to see specific content. To demonstrate this, next we'll update our sidebar to display a "Login" link if the user is logged out, and a "Logout" link if they are logged in.

    Open the base template (/django-locallibrary-tutorial/catalog/templates/base_generic.html) and copy the following text into the sidebar block, immediately before the endblock template tag.

    django
      <ul class="sidebar-nav">
        …
       {% if user.is_authenticated %}
         <li>User: {{ user.get_username }}</li>
         <li>
           <form id="logout-form" method="post" action="{% url 'logout' %}">
             {% csrf_token %}
             <button type="submit" class="btn btn-link">Logout</button>
           </form>
         </li>
       {% else %}
         <li><a href="{% url 'login' %}?next={{ request.path }}">Login</a></li>
       {% endif %}
        …
      </ul>
    

    As you can see, we use if / else / endif template tags to conditionally display text based on whether {{ user.is_authenticated }} is true. If the user is authenticated then we know that we have a valid user, so we call {{ user.get_username }} to display their name.

    We create the login link URL using the url template tag and the name of the login URL configuration. Note also how we have appended ?next={{ request.path }} to the end of the URL. What this does is add a URL parameter next containing the address (URL) of the current page, to the end of the linked URL. After the user has successfully logged in, the view will use this next value to redirect the user back to the page where they first clicked the login link.

    The logout template code is different, because from Django 5 to log out you must POST to the admin:logout URL, using a form with a button. By default this would render as a button, but you can style the button to display as a link. For this example we're using Bootstrap, so we make the button look like a link by applying class="btn btn-link". You also need to append the following styles to /django-locallibrary-tutorial/catalog/static/css/styles.css in order to correctly position the logout link next to all the other sidebar links:

    css
    #logout-form {
      display: inline;
    }
    #logout-form button {
      padding: 0;
      margin: 0;
    }
    

    Try it out by clicking the Login/Logout links in the sidebar. You should be taken to the logout/login pages that you defined in the Template directory above.

    Testing in views

    If you're using function-based views, the easiest way to restrict access to your functions is to apply the login_required decorator to your view function, as shown below. If the user is logged in then your view code will execute as normal. If the user is not logged in, this will redirect to the login URL defined in the project settings (settings.LOGIN_URL), passing the current absolute path as the next URL parameter. If the user succeeds in logging in then they will be returned to this page, but this time authenticated.

    python
    from django.contrib.auth.decorators import login_required
    
    @login_required
    def my_view(request):
        # …
    

    Note: You can do the same sort of thing manually by testing on request.user.is_authenticated, but the decorator is much more convenient!

    Similarly, the easiest way to restrict access to logged-in users in your class-based views is to derive from LoginRequiredMixin. You need to declare this mixin first in the superclass list, before the main view class.

    python
    from django.contrib.auth.mixins import LoginRequiredMixin
    
    class MyView(LoginRequiredMixin, View):
        # …
    

    This has exactly the same redirect behavior as the login_required decorator. You can also specify an alternative location to redirect the user to if they are not authenticated (login_url), and a URL parameter name instead of next to insert the current absolute path (redirect_field_name).

    python
    class MyView(LoginRequiredMixin, View):
        login_url = '/login/'
        redirect_field_name = 'redirect_to'
    

    For additional detail, check out the Django docs here.

    Example — listing the current user's books

    Now that we know how to restrict a page to a particular user, let's create a view of the books that the current user has borrowed.

    Unfortunately, we don't yet have any way for users to borrow books! So before we can create the book list we'll first extend the BookInstance model to support the concept of borrowing and use the Django Admin application to loan a number of books to our test user.

    Models

    First, we're going to have to make it possible for users to have a BookInstance on loan (we already have a status and a due_back date, but we don't yet have any association between this model and a particular user). We'll create one using a ForeignKey (one-to-many) field. We also need an easy mechanism to test whether a loaned book is overdue.

    Open catalog/models.py, and import the settings from django.conf (add this just below the previous import line at the top of the file, so the settings are available to subsequent code that makes use of them):

    python
    from django.conf import settings
    

    Next, add the borrower field to the BookInstance model, setting the user model for the key as the value of the setting AUTH_USER_MODEL. Since we have not overridden the setting with a custom user model this maps to the default User model from django.contrib.auth.models.

    python
    borrower = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    

    Note: Importing the model in this way reduces the work required if you later discover that you need a custom user model. This tutorial uses the default model, so you could instead import the User model directly with the following lines:

    python
    from django.contrib.auth.models import User
    
    python
    borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    

    While we're here, let's add a property that we can call from our templates to tell if a particular book instance is overdue. While we could calculate this in the template itself, using a property as shown below will be much more efficient.

    Add this somewhere near the top of the file:

    python
    from datetime import date
    

    Now add the following property definition to the BookInstance class:

    Note: The following code uses Python's bool() function, which evaluates an object or the resulting object of an expression, and returns True unless the result is "falsy", in which case it returns False. In Python an object is falsy (evaluates as False) if it is: empty (like [], (), {}), 0, None or if it is False.

    python
    @property
    def is_overdue(self):
        """Determines if the book is overdue based on due date and current date."""
        return bool(self.due_back and date.today() > self.due_back)
    

    Note: We first verify whether due_back is empty before making a comparison. An empty due_back field would cause Django to throw an error instead of showing the page: empty values are not comparable. This is not something we would want our users to experience!

    Now that we've updated our models, we'll need to make fresh migrations on the project and then apply those migrations:

    bash
    python3 manage.py makemigrations
    python3 manage.py migrate
    

    Admin

    Now open catalog/admin.py, and add the borrower field to the BookInstanceAdmin class in both the list_display and the fieldsets as shown below. This will make the field visible in the Admin section, allowing us to assign a User to a BookInstance when needed.

    python
    @admin.register(BookInstance)
    class BookInstanceAdmin(admin.ModelAdmin):
        list_display = ('book', 'status', 'borrower', 'due_back', 'id')
        list_filter = ('status', 'due_back')
    
        fieldsets = (
            (None, {
                'fields': ('book', 'imprint', 'id')
            }),
            ('Availability', {
                'fields': ('status', 'due_back', 'borrower')
            }),
        )
    

    Loan a few books

    Now that it's possible to loan books to a specific user, go and loan out a number of BookInstance records. Set their borrowed field to your test user, make the status "On loan", and set due dates both in the future and the past.

    Note: We won't spell the process out, as you already know how to use the Admin site!

    On loan view

    Now we'll add a view for getting the list of all books that have been loaned to the current user. We'll use the same generic class-based list view we're familiar with, but this time we'll also import and derive from LoginRequiredMixin, so that only a logged in user can call this view. We will also choose to declare a template_name, rather than using the default, because we may end up having a few different lists of BookInstance records, with different views and templates.

    Add the following to catalog/views.py:

    python
    from django.contrib.auth.mixins import LoginRequiredMixin
    
    class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
        """Generic class-based view listing books on loan to current user."""
        model = BookInstance
        template_name = 'catalog/bookinstance_list_borrowed_user.html'
        paginate_by = 10
    
        def get_queryset(self):
            return (
                BookInstance.objects.filter(borrower=self.request.user)
                .filter(status__exact='o')
                .order_by('due_back')
            )
    

    In order to restrict our query to just the BookInstance objects for the current user, we re-implement get_queryset() as shown above. Note that "o" is the stored code for "on loan" and we order by the due_back date so that the oldest items are displayed first.

    URL conf for on loan books

    Now open /catalog/urls.py and add a path() pointing to the above view (you can just copy the text below to the end of the file).

    python
    urlpatterns += [
        path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'),
    ]
    

    Template for on-loan books

    Now, all we need to do for this page is add a template. First, create the template file /catalog/templates/catalog/bookinstance_list_borrowed_user.html and give it the following contents:

    django
    {% extends "base_generic.html" %}
    
    {% block content %}
        <h1>Borrowed books</h1>
    
        {% if bookinstance_list %}
        <ul>
    
          {% for bookinst in bookinstance_list %}
          <li class="{% if bookinst.is_overdue %}text-danger{% endif %}">
            <a href="{% url 'book-detail' bookinst.book.pk %}">{{ bookinst.book.title }}</a> ({{ bookinst.due_back }})
          </li>
          {% endfor %}
        </ul>
    
        {% else %}
          <p>There are no books borrowed.</p>
        {% endif %}
    {% endblock %}
    

    This template is very similar to those we've created previously for the Book and Author objects. The only "new" thing here is that we check the method we added in the model (bookinst.is_overdue) and use it to change the color of overdue items.

    When the development server is running, you should now be able to view the list for a logged in user in your browser at http://127.0.0.1:8000/catalog/mybooks/. Try this out with your user logged in and logged out (in the second case, you should be redirected to the login page).

    Add the list to the sidebar

    The very last step is to add a link for this new page into the sidebar. We'll put this in the same section where we display other information for the logged in user.

    Open the base template (/django-locallibrary-tutorial/catalog/templates/base_generic.html) and add the "My Borrowed" line to the sidebar in the position shown below.

    django
     <ul class="sidebar-nav">
       {% if user.is_authenticated %}
       <li>User: {{ user.get_username }}</li>
    
       <li><a href="{% url 'my-borrowed' %}">My Borrowed</a></li>
    
       <li>
         <form id="logout-form" method="post" action="{% url 'admin:logout' %}">
           {% csrf_token %}
           <button type="submit" class="btn btn-link">Logout</button>
         </form>
       </li>
       {% else %}
       <li><a href="{% url 'login' %}?next={{ request.path }}">Login</a></li>
       {% endif %}
     </ul>
    

    What does it look like?

    When any user is logged in, they'll see the My Borrowed link in the sidebar, and the list of books displayed as below (the first book has no due date, which is a bug we hope to fix in a later tutorial!).

    Library - borrowed books by user

    Permissions

    Permissions are associated with models and define the operations that can be performed on a model instance by a user who has the permission. By default, Django automatically gives add, change, and delete permissions to all models, which allow users with the permissions to perform the associated actions via the admin site. You can define your own permissions to models and grant them to specific users. You can also change the permissions associated with different instances of the same model.

    Testing on permissions in views and templates is then very similar to testing on the authentication status (and in fact, testing for a permission also tests for authentication).

    Models

    Defining permissions is done on the model class Meta section, using the permissions field. You can specify as many permissions as you need in a tuple, each permission itself being defined in a nested tuple containing the permission name and permission display value. For example, we might define a permission to allow a user to mark that a book has been returned as shown:

    python
    class BookInstance(models.Model):
        # …
        class Meta:
            # …
            permissions = (("can_mark_returned", "Set book as returned"),)
    

    We could then assign the permission to a "Librarian" group in the Admin site.

    Open the catalog/models.py, and add the permission as shown above. You will need to re-run your migrations (call python3 manage.py makemigrations and python3 manage.py migrate) to update the database appropriately.

    Templates

    The current user's permissions are stored in a template variable called {{ perms }}. You can check whether the current user has a particular permission using the specific variable name within the associated Django "app" — e.g., {{ perms.catalog.can_mark_returned }} will be True if the user has this permission, and False otherwise. We typically test for the permission using the template {% if %} tag as shown:

    django
    {% if perms.catalog.can_mark_returned %}
        <!-- We can mark a BookInstance as returned. -->
        <!-- Perhaps add code to link to a "book return" view here. -->
    {% endif %}
    

    Views

    Permissions can be tested in function view using the permission_required decorator or in a class-based view using the PermissionRequiredMixin. The pattern are the same as for login authentication, though of course, you might reasonably have to add multiple permissions.

    Function view decorator:

    python
    from django.contrib.auth.decorators import permission_required
    
    @permission_required('catalog.can_mark_returned')
    @permission_required('catalog.can_edit')
    def my_view(request):
        # …
    

    A permission-required mixin for class-based views.

    python
    from django.contrib.auth.mixins import PermissionRequiredMixin
    
    class MyView(PermissionRequiredMixin, View):
        permission_required = 'catalog.can_mark_returned'
        # Or multiple permissions
        permission_required = ('catalog.can_mark_returned', 'catalog.change_book')
        # Note that 'catalog.change_book' is permission
        # Is created automatically for the book model, along with add_book, and delete_book
    

    Note: There is a small default difference in the behavior above. By default for a logged-in user with a permission violation:

    • @permission_required redirects to login screen (HTTP Status 302).
    • PermissionRequiredMixin returns 403 (HTTP Status Forbidden).

    Normally you will want the PermissionRequiredMixin behavior: return 403 if a user is logged in but does not have the correct permission. To do this for a function view use @login_required and @permission_required with raise_exception=True as shown:

    python
    from django.contrib.auth.decorators import login_required, permission_required
    
    @login_required
    @permission_required('catalog.can_mark_returned', raise_exception=True)
    def my_view(request):
        # …
    

    Example

    We won't update the LocalLibrary here; perhaps in the next tutorial!

    Challenge yourself

    Earlier in this article, we showed you how to create a page for the current user, listing the books that they have borrowed. The challenge now is to create a similar page that is only visible for librarians, that displays all books that have been borrowed, and which includes the name of each borrower.

    You should be able to follow the same pattern as for the other view. The main difference is that you'll need to restrict the view to only librarians. You could do this based on whether the user is a staff member (function decorator: staff_member_required, template variable: user.is_staff) but we recommend that you instead use the can_mark_returned permission and PermissionRequiredMixin, as described in the previous section.

    Warning: Remember not to use your superuser for permissions based testing (permission checks always return true for superusers, even if a permission has not yet been defined!). Instead, create a librarian user, and add the required capability.

    When you are finished, your page should look something like the screenshot below.

    All borrowed books, restricted to librarian

    Summary

    Excellent work — you've now created a website where library members can log in and view their own content, and where librarians (with the correct permission) can view all loaned books and their borrowers. At the moment we're still just viewing content, but the same principles and techniques are used when you want to start modifying and adding data.

    In our next article, we'll look at how you can use Django forms to collect user input, and then start modifying some of our stored data.

    See also