# How to

(create_a_list)=
## 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:


```python
basket = ["Bread", "Biscuits", "Coffee"]
basket
```




    ['Bread', 'Biscuits', 'Coffee']



We can add to our list by appending to it:


```python
basket.append("Tea")
basket
```




    ['Bread', 'Biscuits', 'Coffee', 'Tea']



We can also combine lists together:


```python
other_basket = ["Toothpaste"]
basket = basket + other_basket
basket
```




    ['Bread', 'Biscuits', 'Coffee', 'Tea', 'Toothpaste']



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


```python
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:


```python
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`:


```python
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:


```python
x_cubed(2)
```




    8




```python
x_cubed(5)
```




    125




```python
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 RUM IF CONDITION IS NOT TRUE
```
````

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

$$
    f(x) = \begin{cases}
            x ^ 3&\text{ if }x < 0\\
            x ^ 2&\text{ otherwise}
            \end{cases}
$$


```python
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
```


```python
f(0)
```




    0




```python
f(-1)
```




    -1




```python
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:


```python
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
```


```python
get_price_of_item("Toothpaste")
```




    3.5




```python
get_price_of_item("Biscuits")
```




    3




```python
get_price_of_item("Rollerblades")
```




    0



(create_a_list_using_a_list_comprehension)=
## 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:


```python
new_list = [object for object in old_list]
```


```python
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:


```python
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:


```python
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:


```python
sum(f(object) for object in old_list)
```

This gives the same result as:


```python
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:


```python
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)
```
````


```python
import random

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




    'Tea'



## 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:


```python
import random

random.random()
```




    0.4880796961634797



## 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)
```
````


```python
import random

random.seed(0)
random.random()
```




    0.8444218515250481




```python
random.random()
```




    0.7579544029403025




```python
random.seed(0)
random.random()
```




    0.8444218515250481



8518864fbdf07bf058d1f6f5721395ecdf2cc0b2
ipynb
Jupyter Notebook
book/tools-for-mathematics/06-probability/how/.main.md.bcp.ipynb
daffidwilde/pfm
dcf38faccee3c212c8394c36f4c093a2916d283e
MIT
book/tools-for-mathematics/06-probability/how/.main.md.bcp.ipynb
daffidwilde/pfm
dcf38faccee3c212c8394c36f4c093a2916d283e
MIT
book/tools-for-mathematics/06-probability/how/.main.md.bcp.ipynb
daffidwilde/pfm
dcf38faccee3c212c8394c36f4c093a2916d283e
MIT
Qwen/Qwen-72B
1. YES
2. YES