How to#

Create a list#

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

Usage

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

For example:

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

You can insert an element to the end of a list by appending to it:

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

You can also combine lists together:

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

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

basket[3]
'Tea'

Define a function#

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

Usage

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

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 you to document your code clarity. You 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 call it using the ():

Usage

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}\]

Run code based on a condition#

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

Usage

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 you 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 0:

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#

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

Usage

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 you would have:

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

In Python this is done as follows:

:class: tip

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]

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

For example you 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]

Summing items in a list#

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

sum([1, 2, 3])
6

You can also directly use 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:

Usage

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 more 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 use the random library and the choice tool.

Usage

random.choice(collection)
import random

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

Sample a random number#

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

Usage

random.random()

For example:

import random

random.random()
0.785940310662359

Reproduce random events#

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

Usage

random.seed(int)
import random

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