How to#

Create a list#

To create a list which is an ordered collection of objects that can be changed we use the [] brackets.

Tip

collection = [value_1, value_2, value_3, …, value_n]

For example:

basket = ["Bread", "Biscuits", "Coffee"]
basket
['Bread', 'Biscuits', 'Coffee']

We can add to our list by appending to it:

basket.append("Tea")
basket
['Bread', 'Biscuits', 'Coffee', 'Tea']

We can also combine lists together:

other_basket = ["Toothpaste"]
basket = basket + other_basket
basket
['Bread', 'Biscuits', 'Coffee', 'Tea', 'Toothpaste']

As for tuples we can also access elements using their indices:

basket[3]
'Tea'

Define a function#

We define a function using the def keyword (short for define):

Tip

def name(variable1, variable2, ...):
    """
    A docstring between triple quotation to describe what is happening
    """
    INDENTED BLOCK OF CODE
    return output

We can for example define \(f:\mathbb{R}\to\mathbb{R}\) given by \(f(x) = x ^ 3\) using the following:

def x_cubed(x):
    """
    A function to return x ^ 3
    """
    return x ** 3

It is important to include the docstring as this allows us to make sure our code is clear. We can access that docstring using help:

help(x_cubed)
Help on function x_cubed in module __main__:

x_cubed(x)
    A function to return x ^ 3

Call a function#

Once a function is defined we call it using the ():

Tip

name(variable1, variable2, ...)

For example:

x_cubed(2)
8
x_cubed(5)
125
import sympy as sym

x = sym.Symbol("x")
x_cubed(x)
\[\displaystyle x^{3}\]

Conditional running of code#

To run code depending on whether or not a particular condition is met we use something called an if statement.

Tip

if condition:
    INDENTED BLOCK OF CODE TO RUN IF CONDITION IS TRUE
else:
    OTHER INDENTED BLOCK OF CODE TO RUN IF CONDITION IS NOT TRUE

These if statements are most useful when combined with functions. For example we can define the following function:

\[\begin{split} f(x) = \begin{cases} x ^ 3&\text{ if }x < 0\\ x ^ 2&\text{ otherwise} \end{cases} \end{split}\]
def f(x):
    """
    A function that returns x ^ 3 if x is negative.
    Otherwise it returns x ^ 2.
    """
    if x < 0:
        return x ** 3
    return x ** 2
f(0)
0
f(-1)
-1
f(3)
9

Here is another example of a function that returns the price of a given item, if the item is not specific in the function then the price is free:

def get_price_of_item(item):
    """
    Returns the price of an item:

    - 'Bread': 2
    - 'Biscuits': 3
    - 'Coffee': 1.80
    - 'Tea': .50
    - 'Toothpaste': 3.50

    Other items will give a price of 0.
    """
    if item == "Bread":
        return 2
    if item == "Biscuits":
        return 3
    if item == "Coffee":
        return 1.80
    if item == "Tea":
        return 0.50
    if item == "Toothpaste":
        return 3.50
    return 0
get_price_of_item("Toothpaste")
3.5
get_price_of_item("Biscuits")
3
get_price_of_item("Rollerblades")
0

Create a list using a list comprehension#

We can create a new list from an old list using a list comprehension.

Tip

collection = [f(item) for item in iterable]

This corresponds to building a set from another set in the usual mathematical notation:

\[ S_2 = \{f(x)\text{ for x in }S_1\} \]

If \(f(x)=x - 5\) and \(S_1=\{2, 5, 10\}\) then we would have:

\[ S_2 = \{-3, 0, 5\} \]

In Python this is done as follows:

new_list = [object for object in old_list]
s_1 = [2, 5, 10]
s_2 = [x - 5 for x in s_1]
s_2
[-3, 0, 5]

We can combine this with functions to write succinct efficient code.

For example we can compute the price of a basket of goods using the following:

basket = ["Tea", "Tea", "Toothpaste", "Bread"]
prices = [get_price_of_item(item) for item in basket]
prices
[0.5, 0.5, 3.5, 2]

Adding items in a list#

We can compute the sum of items in a list using the sum tool:

sum([1, 2, 3])
6

We can also directly use the sum without specifically creating the list. This corresponds to the following mathematical notation:

\[ \sum_{s\in S}f(s) \]

and is done using the following:

sum(f(object) for object in old_list)

This gives the same result as:

sum([f(object) for object in old_list])

but it is not as efficient.

Here is an example of getting the total price of a basket of goods:

basket = ["Tea", "Tea", "Toothpaste", "Bread"]
total_price = sum(get_price_of_item(item) for item in basket)
total_price
6.5

Sample from an iterable#

To randomly sample from any collection of items we use the random library and the choice tool.

Tip

random.choice(collection)
import random

basket = ["Tea", "Tea", "Toothpaste", "Bread"]
random.choice(basket)
'Bread'

Sample a random number#

To sample a random number between 0 and 1 we use the random library and the random tool.

Tip

random.random()

For example:

import random

random.random()
0.4102927287300423

Reproduce random events#

The random numbers processes generated by the Python random module are what are called pseudo random which means that we can get a computer to reproduce them by seeding the random process.

Tip

random.seed(int)
import random

random.seed(0)
random.random()
0.8444218515250481
random.random()
0.7579544029403025
random.seed(0)
random.random()
0.8444218515250481