{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 7 | PYTHON COLLECTIONS" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

This chapter of an Introduction to Health Data Science by Dr JH Klopper is licensed under Attribution-NonCommercial-NoDerivatives 4.0 International

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ## Introduction" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Previous notebooks showed the creation and assignment of single values such as numbers and strings to variables. Python allows for the combination of such elements into collections." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are four types of collections. These are lists, tuples, dictionaries, and sets. Understanding these collection types is not just about learning Python syntax. It is about the tools used to handle complex, real-world problems that revolve around data. As the old adage goes, _data is the new oil_, and Python collections are the pipelines used to transport and process this data." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ## Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A Python __list__ is a built-in data structure that allows for the storage of a collection of items. The items, known as elements, can be of any type. Integers, strings, floats, or even other complex objects, such as other lists, dictionaries, and custom objects. This makes lists incredibly versatile and adaptable to a wide variety of tasks." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A Python list can be created using square bracket notation. The elements are separated by commas. The following code creates a list of integers and uses the `type` function to confirm the data type of a list." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a list of five integers\n", "[1, 2, 3, 4, 5]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Type of the list\n", "type([1, 2, 3, 4, 5])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The elements can alse be of different types. The following code creates a list of integers and strings." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 'one', 'two', 'three', 'four', 'five']" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a list of five integers and five strings\n", "[1, 2, 3, 4, 5, \"one\", \"two\", \"three\", \"four\", \"five\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python lists are ordered, meaning the order in which elements are added to the list is preserved. Each element in a list has a specific position, identified by its index. Indexing in Python is zero-based, which means the first element is at index $0$, the second element is at index $1$, and so forth. Negative indexing is also supported, where the last element is at index $-1$, the second last at $-2$, and so on, making it possible to access the list from both ends." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The index value can be used to retrieve an element from a list. The list object below is assigned to the variable `my_list`. The first element in the list is retrieved using the index value $0$." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# Create a lsit of five random integers and assign it to the variable my_list\n", "my_list = [7, 4, 8, 2, 9]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Retrieve the first element of the list\n", "my_list[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first element is indeed $7$. The last element can be retrieved using the index value $-1$. This is useful when the length of the list is not known and particularly long." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Retrieve the last element of the list\n", "my_list[-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that in this short list, it is easy to recognize that the last element has an index of $4$." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Retrieve the last element of the list\n", "my_list[4]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Contiguous elements can be retrieved using a range of index values. This process is termed slicing. The following code retrieves the first three elements of the list. The first three elements have indices $0$, $1$, and $2$." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[7, 4, 8]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Retrieve the first three elements of the list\n", "my_list[0:3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "While the range is specified as $0:3$, the element at index $3$ is not included in the result. This is because the range is exclusive of the last index value." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The colon symbol, `:`, can be used to retrieve all elements in a list up to a specific index value. The following code retrieves all elements up to index $3$." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[7, 4, 8]" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Retrieve the first three elements of the list\n", "my_list[:3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The same process can be used to retrieve all elements from a specific index value to the end of the list. The following code retrieves all elements from index $3$ to the end of the list." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 9]" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Retrieve all elements from index 3\n", "my_list[3:]" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[8, 2, 9]" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Retrieve the last three elements of the list\n", "my_list[-3:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of the key characteristics of a Python list is its mutability. In other words, once a list is created, its elements can be modified, added, or removed, allowing for dynamic and flexible data manipulation. Functions like `append`, `extend`, and `pop`, among others, provide the capability to modify lists after they have been created." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The index is specified before assigning the new value. The following code changes the first element in the list to the string `'first'`." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['First', 4, 8, 2, 9]" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Change the first element of the list to 'First\n", "my_list[0] = 'First'\n", "my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The code below demonstrates reassignment with anotehr list to show that lists can also be elements of a list object. Such lists of lists are known as nested lists." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['First', 4, 8, 2, ['one', 'two', 'three']]" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Change the last element of the list to the list ['one', 'two', 'three']\n", "my_list[-1] = ['one', 'two', 'three']\n", "my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is clear from using the `len` function that the list still has only five elements, even though the last element is a nested list with three elements." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the length of the list\n", "len(my_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The nested list can be accessed using the index of the outer list." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['one', 'two', 'three']" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Retrieve the last element of the list\n", "my_list[-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To retrieve elements in a nested list, the index of the outer list is specified first, followed by the index of the inner list. The following code retrieves the first element of the nested list." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'one'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Retrieve the first element of the last element of the list\n", "my_list[-1][0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `append` method adds an element to the end of a list. The following code adds the integer $6$ to the end of the list." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `extend` method can be used to add elements to a list as well. The following code adds the elements $10$, $11$, and $12$ to `my_list`. Note that the values are passed as a list." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['First', 4, 8, 2, ['one', 'two', 'three'], 10, 11, 12]" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Extend the list with the elements 10, 11, and 12\n", "my_list.extend([10, 11, 12])\n", "my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `pop` method removes the last element from a list. The following code removes the last element, which is the integer $12$, from `my_list`." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['First', 4, 8, 2, ['one', 'two', 'three'], 10, 11]" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Remove the last element of the list\n", "my_list.pop()\n", "my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By passing an index value to the `pop` method, a specific element can be removed from a list. The following code removes the element at index $2$ from `my_list`." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['First', 4, 2, ['one', 'two', 'three'], 10, 11]" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Remove the element at index 2\n", "my_list.pop(2) # The value 8 at index number 2 is removed\n", "my_list" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['First', 4, 2, ['one', 'two', 'three'], 10, 11, 6]" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Append the number 6 to the list\n", "my_list.append(6)\n", "my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `insert` method adds an element to a list at a specific index. The following code adds the string `'inserted'` to `my_list` at index $2$." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['First', 4, 'inserted', 2, ['one', 'two', 'three'], 10, 11, 6]" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Insert the string 'inserted' at index 2\n", "my_list.insert(2, 'inserted')\n", "my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition to this, Python lists support operations like concatenation, repetition, and membership tests. Two new list are created below and the addigion symbol, `+`, is used to concatenate them." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "# Create a two new lists of integers\n", "my_list1 = [1, 2, 3, 4, 5]\n", "my_list2 = [6, 7, 8, 9, 10]" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Concatenate the two lists\n", "my_list1 + my_list2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The elements of `my_list1` is repeated three times using the multiplication symbol, `*`, below." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Repeat my_list1 three times\n", "my_list1 * 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `in` keyword is used to determine of a specified element is contained in a list. Below it is used below to determine if the integer $3$ is an element of `my_list1`." ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Determine of the numner 5 is in my_list1\n", "5 in my_list1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `reverse` method revereses the order of the elements of a list object." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[5, 4, 3, 2, 1]" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Reverse the list\n", "my_list1.reverse()\n", "my_list1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Instead of using bracket notation, the `list` function can be used to create a list. The following code creates a list of integers from $0$ to $9$ using the `range` function." ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use the list function and the range function to create a list of integers from 0 to 9\n", "list(range(10))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Passing a string to the `list` function, uses the individual characters of the string as elements of the list." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['I', ' ', 'l', 'o', 'v', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n']" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Created a list containing the string 'I love Python'\n", "list('I love Python')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python lists are typically used when there's a need for a collection of data that will undergo modification during the course of a program, such as adding, removing, or changing elements. They form a foundational part of Python programming and offer a flexible and intuitive way to handle ordered collections of data." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ## Tuples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A tuple is similar to a list, other than the fact that tuples are immutable. The tuple or its elements cannot be changed after being created." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Parentheses are used instead of square brackets to denote a tuple (although they are not strictly required). The `tuple` function similarly generates a tuple object." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The code below generates a tuple, assigning elements separated by commas. No parentheses are used." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(2, 4, 5, 7, 'ring')" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a tuple of five integers and assign it to the variable tuple_1\n", "tuple_1 = 2, 4, 5, 7, 'ring' # Simply state elements\n", "tuple_1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `type` function indicates that `tuple_1`` is indeed a tuple object." ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Type of the tuple\n", "type(tuple_1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The elements of a tuple can be of many data types." ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 'three', ['P', 'y', 't', 'h', 'o', 'n'])" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a tuple with the elements 1, 2, 'three', and the list 'Python' and assign it to the variable tuple_2\n", "tuple_2 = (1, 2, 'three', list('Python')) # Use parentheses\n", "tuple_2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Indexing and slicing of tuples is similar to that of lists. The following code retrieves the first element of `tuple_1`." ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Retrieve the first element of tuple_1\n", "tuple_1[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since tuples are immutable, the values of elemenst cannot be changed. Nor can elements be added or removed from a tuple." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other than using the indices for each element of a tuple, a computer variable name can be assigned to each element of a tuple. The code below generates a tuple object, `languages``. The tuple contains three string objects." ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('Python', 'R', 'Julia')" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a tuple with the string elements 'Python', 'R', and 'Julia' and assign it to the variable langauges\n", "languages = ('Python', 'R', 'Julia')\n", "languages" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each element is assigned a variable name." ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "# Assign each element of the tuple to a separate variable, using the variable names one, two, and three\n", "one, two, three = languages" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using the variable names, the elements of the tuple can be retrieved." ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Python'" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Retrieve the object in one\n", "one" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `zip` function is an interesting and useful function. It combines elements of lists into a list of tuples. The code below generates two list object. In the code below, the first, `names`, contains three first names. The second, `surnames` contains a list of three last names." ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "names = ['Mary', 'Anne', 'Rene']\n", "surnames = ['Johnstone', 'Barnes', 'Le Roux']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `zip` function is used by passing the two list objects as arguments. All of these are passed as an argument to the `list`` function. The result is a list of tuples, where each element of a tuple comes from an ordered pairing of the original list objects. Note therefor, that the original list objects must have the same length (the same number of elements)." ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[('Mary', 'Johnstone'), ('Anne', 'Barnes'), ('Rene', 'Le Roux')]" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use the zip function to create a list of tuples\n", "list(zip(names, surnames))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A list of tuples can be unzipped using `*` notation." ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "# Generate a list of tuples (each with three elements)\n", "data_set = [('Anna', 'Rogers', 33), ('Susan', 'Roberts', 25), ('Rene', 'Du Bois', 28)]\n", "\n", "# Unzip the thee element tuples\n", "names, lastnames, ages = zip(*data_set)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('Anna', 'Susan', 'Rene')" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the names\n", "names" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('Rogers', 'Roberts', 'Du Bois')" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the lastnames\n", "lastnames" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(33, 25, 28)" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the ages\n", "ages" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Task: Create a tuple named `primes` containing the first seven prime numbers. Then use indexing to return the last three primes numbers in the tuple." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ## Dictionaries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dictionaries are key-value pairs. They are very useful and powerful Python collections and form the basis of many data structures in Python." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `dict` function creates a dictionary. It is much more common to see the use of curly braces, though. The key and the value are separated by a colon, and each key-value pair is separated by a comma." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The code cell below is used to generate data for a subject in a clinical research project. The variable name is chosen as the study protocol identity of each participant." ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "# Generate a dictionary\n", "id345 = {'First Name':'Jenny', 'Last Name':'Gregory', 'Age':48, 'Heart Rate':75}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `keys` method returns a `dict_keys` object that contains a list of the keys in a dictionary." ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_keys(['First Name', 'Last Name', 'Age', 'Heart Rate'])" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the keys of the dictionary\n", "id345.keys()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `values` method returns a `dict_values` object that contains alist of all the values." ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_values(['Jenny', 'Gregory', 48, 75])" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the values of the dictionary\n", "id345.values()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The key can be used as an index to retrieve a value." ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Jenny'" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the value for the 'Firt Name' key\n", "id345['First Name']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `get` method can also be used. Where the index notation returns an error if a key is not found, the `get` method returns nothing instead of an error message." ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [], "source": [ "id345.get('Surname') # No such key" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Task: Generate a Python dictionary object assigned to the variable `my_dict`, that contains the keys \n", "`1`, `2`, `3`, and `4` with the corresponing values `A`, `B`, `C` and `D`. Note how the keys can be numbers. Return a Python list object from `my_dict` that contains the values of the dictionary." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Solution" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['A', 'B', 'C', 'D']" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Generate a dictionary using the dict function\n", "my_dict = dict([(1, 'A'), (2, 'B'), (3,'C'), (4,'D')])\n", "\n", "# Return a list of the values of the dictionary\n", "list(my_dict.values())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ## Sets" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A Python set object is an unordered collection of unique elements. In this regard a Python set is much like a mathematical set." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A set is generated using curly brackets or the `set` function. The latter takes a list as argument." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The code below generates a set using braces and set notation. Note that in eacn case there is a duplication of elements. A set object only contains unique elements and discards the duplicates." ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4}" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Generate set with the elements 1, 2, 3, 4, 4, 4, 4, 1\n", "set_1 = {1, 2, 3, 4, 4, 4, 4, 1}\n", "set_1 # Call object and print to the scren" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4}" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use the set function instead\n", "set_1 = set([1, 2, 3, 4, 4, 4, 4, 1])\n", "set_1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `add` method adds an element to a set." ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4, 7}" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Add the element 7 to the set\n", "set_1.add(7)\n", "set_1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `remove` method removes an element from a set. Note that it is not the index that is used." ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 7}" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Remove the element 4 from the set\n", "set_1.remove(4)\n", "set_1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As with mathematical sets, the union and intersetcion of sets can be determined. The `union` method returns a set that contains all the elements of both sets and the `intersection` method returns a set that contains only the elements that are common to both sets." ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a', 'b', 'c', 'd', 'e', 'f'}" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# First set\n", "set_A = {'a', 'a', 'a', 'b', 'c', 'd', 'e', 'f', 'e', 'a'}\n", "set_A" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a', 'c', 'f', 'g'}" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Second set\n", "set_B = {'a', 'c', 'c', 'f', 'g'}\n", "set_B" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a', 'b', 'c', 'd', 'e', 'f', 'g'}" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the union of the two sets using the union method\n", "set_A.union(set_B)" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a', 'c', 'f'}" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the intersection of the two sets using the intersection method\n", "set_A.intersection(set_B)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As alternative, the `|` and `&` operators can be used to determine the union and intersection of sets, respectively." ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a', 'b', 'c', 'd', 'e', 'f', 'g'}" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the union of the two sets using the pipe operator\n", "set_A | set_B" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a', 'c', 'f'}" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the intersection of the two sets using the & operator\n", "set_A & set_B" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The set difference operation removes all the elements in the intersection of two sets from the first set. In this sense, it is similar to subtraction. The code below uses the `difference` method to calculate set difference." ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'b', 'd', 'e'}" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the difference between the two sets using the difference method\n", "set_A.difference(set_B)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Task: Reverse the order of the set difference in the code cell above and determine if the set difference between the objetcs `set_A` and `set_B` is the same as the set difference between the sets `set_B` and `set_A`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The symmetric difference between sets subtracsts the intersection of the sets from the union of the sets. The code cell below uses the `symmetric_difference` method to calculate the set difference between two sets." ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'b', 'd', 'e', 'g'}" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return the symmetric difference between the two sets using the symmetric_difference method\n", "set_A.symmetric_difference(set_B)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ## List comprehension" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python has a powerful feature called comprehension. It is most commonly used in terms of lists and is then termed __list comprehension__. Comprehension combines for loops into the creation of a collection." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Below, list comprehension is used to generate a list that contains the square of the first $10$ natural numbers. Square bracket notation is used for list comprehension. The first expression is the recipe instruction. In this case, a placeholder variable, `x`. Then follows the `for` loop with the in keyword." ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use list comprehension to create a list of the first 10 square natural numbers\n", "[x**2 for x in range(1, 11)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Conditionals can be used as well. Below, only the squares of the natural numbers greater than $5$ is squared." ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[36, 49, 64, 81, 100]" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Squares of natural numbers larger than 5\n", "[n**2 for n in range(1, 11) if n > 5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `if` statement can also contain a recipe. Below, only cases where the square is smaller than $50$ is included." ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 9, 16, 25, 36, 49]" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Only include elements that are less than 50\n", "[n**2 for n in range(1, 11) if n**2 < 50]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Quiz questions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Questions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. How do you define a list in Python? \n", "\n", "2. How do you access the third element of a Python list named `my_list`?\n", "\n", "3. How can you add the element \"new_item\" to the end of an existing list named `my_list`?\n", "\n", "4. *How do you create a Python tuple with the items \"apple\", \"banana\", and \"cherry\"?\n", "\n", "5. How do you access the first element of a Python tuple named `my_tuple`?\n", "\n", "6. How do you define a dictionary in Python with keys \"name\", \"age\" and values \"John Doe\", 30?\n", "\n", "7. How can you retrieve the value for the key \"name\" from the dictionary `my_dict`\n", "\n", "8. How can you change the value associated with the key \"age\" in the dictionary `my_dict` to 35?\n", "\n", "9. How can you add a new key-value pair \"city\":\"New York\" to the dictionary `my_dict`?\n", "\n", "10. *How do you create a set in Python with the items \"apple\", \"banana\", and \"cherry\"?\n", "\n", "11. How do you add the item \"orange\" to an existing set `my_set`?\n", "\n", "12. How do you remove the item \"banana\" from the set `my_set`?\n", "\n", "13. What is the length of a list `my_list` with elements `[1, 2, 3, 4, 5]`?\n", "\n", "14. What will be the result of `my_list * 2` if `my_list` is `[1, 2, 3]`?\n", "\n", "15. What is the result of `set([1,2,2,3,4,4,4,5,5])`?\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] } ], "metadata": { "kernelspec": { "display_name": "datascience", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.1" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }