Further information#

Are there other ways to access elements in tuples?#

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

  1. Indexing (seen here)

  2. Negative indexing

  3. Slicing (selecting a number of elements)

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 the creation of the instructions to build something without building it.

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

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 the sum command, the \(\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.