Further information#

How does tuple indexing work?#

We have seen in this chapter how to access a single element in a tuple. There are various ways of indexing tuples:

  1. Indexing (what we have seen here)

  2. Negative indexing (indexing starting from the end)

  3. Slicing (selecting a number of elements)

This document gives good information on this: https://www.programiz.com/python-programming/tuple

Why does range, itertools.permutations and itertools.combinations not directly give the elements?#

When you run either of the three range, itertools.permutations or itertools.combinations tools this is an example of creating a generator. This allows us to create the instructions to build something without building it.

In practice this means that we can create large sets without needing to generate them until we wanted to.

How does the summation notation \(\sum\) correspond to the code?#

The sum command corresponds to the mathematical \(\sum\) notation. Here are a few examples showing not only the sum command, \(\sum\) notation but also the prose describing:

Mathematics

Python

Prose

\[\sum_{i=1}^{100}i ^2\]
sum(i ** 2 for i in range(1, 101))

The sum of the square of the integers from 1 to 100 (inclusive).

\[\begin{split}\sum_{\begin{array}{c}i=1\\\text{if }i\text{ is prime}\end{array}}^{100}i ^2\end{split}\]
sum(i ** 2 for i in range(1, 101) if sym.isprime(i))

The sum of the square of the integers from 1 to 100 (inclusive) if they are prime.

\[\begin{split}\sum_{\begin{array}{c}i\in{S}\\\text{if }i\text{ is prime}\end{array}}i ^2\end{split}\]
sum(i ** 2 for i in S if sym.isprime(i))

The sum of the square of the elements in the collection \(S\) if they are prime.