<jupyter_start><jupyter_text>How to(create_a_list)= Create a listTo create a list which is an ordered collection of objects that **can** bechanged we use the `[]` brackets.````{tip}```collection = [value_1, value_2, value_3, …, value_n]```````For example:<jupyter_code>basket = ["Bread", "Biscuits", "Coffee"]
basket<jupyter_output><empty_output><jupyter_text>We can add to our list by appending to it:<jupyter_code>basket.append("Tea")
basket<jupyter_output><empty_output><jupyter_text>We can also combine lists together:<jupyter_code>other_basket = ["Toothpaste"]
basket = basket + other_basket
basket<jupyter_output><empty_output><jupyter_text>As for tuples we can also access elements using their indices:<jupyter_code>basket[3]<jupyter_output><empty_output><jupyter_text>Define a functionWe 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:<jupyter_code>def x_cubed(x):
    """
    A function to return x ^ 3
    """
    return x ** 3<jupyter_output><empty_output><jupyter_text>It is important to include the *docstring* as this allows us to make sure ourcode is clear. We can access that docstring using `help`:<jupyter_code>help(x_cubed)<jupyter_output>Help on function x_cubed in module __main__:

x_cubed(x)
    A function to return x ^ 3<jupyter_text>Call a functionOnce a function is defined we call it using the `()`:````{tip}```name(variable1, variable2, ...)```````For example:<jupyter_code>x_cubed(2)
x_cubed(5)
import sympy as sym

x = sym.Symbol("x")
x_cubed(x)<jupyter_output><empty_output><jupyter_text>Conditional running of codeTo run code depending on whether or not a particular condition is met we usesomething called an `if` statement.````{tip}```if condition:    INDENTED BLOCK OF CODE TO RUN IF CONDITION IS TRUEelse:    OTHER INDENTED BLOCK OF CODE TO RUM IF CONDITION IS NOT TRUE```````These `if` statements are most useful when combined with functions. For examplewe can define the following function:$$    f(x) = \begin{cases}            x ^ 3&\text{ if }x < 0\\            x ^ 2&\text{ otherwise}            \end{cases}$$<jupyter_code>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)
f(-1)
f(3)<jupyter_output><empty_output><jupyter_text>Here is another example of a function that returns the price of a given item, ifthe item is not specific in the function then the price is free:<jupyter_code>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")
get_price_of_item("Biscuits")
get_price_of_item("Rollerblades")<jupyter_output><empty_output><jupyter_text>(create_a_list_using_a_list_comprehension)= Create a list using a list comprehensionWe 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 mathematicalnotation:$$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:```pythonnew_list = [object for object in old_list]```<jupyter_code>s_1 = [2, 5, 10]
s_2 = [x - 5 for x in s_1]
s_2<jupyter_output><empty_output><jupyter_text>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:<jupyter_code>basket = ["Tea", "Tea", "Toothpaste", "Bread"]
prices = [get_price_of_item(item) for item in basket]
prices<jupyter_output><empty_output><jupyter_text>Adding items in a listWe can compute the sum of items in a list using the `sum` tool:<jupyter_code>sum([1, 2, 3])<jupyter_output><empty_output><jupyter_text>We can also directly use the `sum` without specifically creating the list. Thiscorresponds to the following mathematical notation:$$    \sum_{s\in S}f(s)$$and is done using the following:```pythonsum(f(object) for object in old_list)```This gives the same result as:```pythonsum([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:<jupyter_code>basket = ["Tea", "Tea", "Toothpaste", "Bread"]
total_price = sum(get_price_of_item(item) for item in basket)
total_price<jupyter_output><empty_output><jupyter_text>Sample from an iterableTo randomly sample from any collection of itemswe use the random library and the `choice` tool.````{tip}```random.choice(collection)```````<jupyter_code>import random

basket = ["Tea", "Tea", "Toothpaste", "Bread"]
random.choice(basket)<jupyter_output><empty_output><jupyter_text>Sample a random numberTo sample a random number between 0 and 1 we use the random library and the`random` tool.````{tip}```random.random()```````For example:<jupyter_code>import random

random.random()<jupyter_output><empty_output><jupyter_text>Reproduce random eventsThe random numbers processes generated by the Python random module are what arecalled pseudo random which means that we can get a computer to reproduce them by**seeding** the random process.````{tip}```random.seed(int)```````<jupyter_code>import random

random.seed(0)
random.random()
random.random()
random.seed(0)
random.random()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12577875063141944, 'fraction_numerical': 0.012796767132513891, 'mean_word_length': 5.104830421377184, 'pattern_counts': {'":': 5, '<': 66, '<?xml version=': 0, '>': 64, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '397411', 'license': 'MIT', 'n_tokens_mistral': 2068, 'n_tokens_neox': 1951, 'n_words': 637, 'path': 'book/tools-for-mathematics/06-probability/how/.main.md.bcp.ipynb', 'repo_name': 'daffidwilde/pfm', 'size': '5939'}