{ "cells": [ { "cell_type": "markdown", "id": "64b81fcd", "metadata": { "id": "21mQxEPhTKl9" }, "source": [ " \n", "\n", "# **Lists**" ] }, { "cell_type": "markdown", "id": "81deb99f", "metadata": { "id": "NGbpwin1ZhMy" }, "source": [ "## Creating a list\n", "So far, we learned about simple data types like `int`, `float`, `bool`, and `str`. Python also offers a range of complex data types that allow us to store multiple related values (items) in a single variable and work with them at once. This is very useful in real world applications.\n", "\n", "Each value in a list is called an __item__. List items are __ordered, changeable, and allow duplicate values__. A list is created by placing all the items (elements) inside square brackets [ ], separated by commas. It can have any number of items that can be of different types (integer, float, string etc.). A list can also have another list (a so-called sublist) as an item. A list with another list as an item is called a __nested list__. Below are some examples:" ] }, { "cell_type": "code", "execution_count": 1, "id": "58619c4d", "metadata": { "id": "d3Wuf7fFY3Jc" }, "outputs": [], "source": [ "empty_list=[]\n", "\n", "numbers=[0,1,2,3,4,5,6]\n", "\n", "strings=[\"hello\", \"there\", \"this\", \"is\", \"Python\", \"handbook\"]\n", "\n", "mixed=[1, 2.5,\"python\", True]\n", "\n", "nested_list = [3, [1.5, 2], [True, False], \"\"]" ] }, { "cell_type": "code", "execution_count": 2, "id": "601747ca", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "nVZnR9XenhS2", "outputId": "7457a1a8-d09e-4b0c-fcaa-e61703591cd7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3, [1.5, 2], [True, False], '']\n" ] } ], "source": [ "# Let's print the nested_list:\n", "print(nested_list)" ] }, { "cell_type": "markdown", "id": "393a4c43", "metadata": { "id": "hW48ivHy2Ivx" }, "source": [ "## List indexing\n", "To access the items in a list we use their index. Items are indexed in two ways:\n", "* __positive indexing__: the first item has index [0] , the second item has index [1], etc.\n", "* __negative indexing__: We can also use negative indexing in Python. It counts the items backwards from the end of the list, starting at -1. Below you can see an example of a list with positive and negative indices:\n", "\n", "`strings=[\"hello\",\"there\",\"this\",\"is\",\"Python\",\"handbook\"]`\n", "\n", "\n", "|List: strings |'hello'|'there'| 'this'|'is'|'python'|'handbook'|\n", "|--------------|-------|-------|-------|----|--------| ---------|\n", "|positive index| 0\t | 1| 2 | 3 | 4 | 5 |\n", "|negative index| -6 \t | -5 | -4 | -3 | -2 | -1 |\n", "\n", "Note that accessing an index which does not exist generates an error. For a nested list, we first provide the index of the main list and then the index for the list that is stored within the main list." ] }, { "cell_type": "code", "execution_count": 3, "id": "ab5a9a8c", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "8LzV8Xc12-Ai", "outputId": "a6a806fb-7133-4dc8-e61f-ceceb94611bb" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n" ] } ], "source": [ "numbers=[0,1,2,3,4,5,6]\n", "print(numbers[0]) # positive indexing" ] }, { "cell_type": "code", "execution_count": 4, "id": "80943b31", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "euWavUrHhGQD", "outputId": "a7a6e56c-e839-46e2-ea57-81392cd20442" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "there\n" ] } ], "source": [ "strings=[\"hello\",\"there\",\"this\",\"is\",\"Python\",\"handbook\"]\n", "print(strings[1]) # positive indexing" ] }, { "cell_type": "code", "execution_count": 5, "id": "5eaaf694", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "tn65Li_ShFrJ", "outputId": "11051d08-c3a7-42e5-a39e-7eff4853328a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[True, False]\n" ] } ], "source": [ "nested_list = [3, [1.5, 2], [True, False], \"\"]\n", "print(nested_list[2]) # positive indexing" ] }, { "cell_type": "code", "execution_count": 6, "id": "97473be8", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "uodAPP_7hA7m", "outputId": "2b629353-c2d0-4538-f378-a407bb146808" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n" ] } ], "source": [ "nested_list = [3, [1.5, 2], [True, False], \"\"]\n", "print(nested_list[2][1]) # nested list indexing" ] }, { "cell_type": "code", "execution_count": 7, "id": "eae703d8", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "c9QD3N7MhC7c", "outputId": "8b92f00a-de2c-4932-e5d3-1039d6c6bf84" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Python\n" ] } ], "source": [ "strings=[\"hello\",\"there\",\"this\",\"is\",\"Python\",\"handbook\"]\n", "print(strings[-2]) # negative indexing" ] }, { "cell_type": "code", "execution_count": 8, "id": "51a51f77", "metadata": { "id": "qOPbdL4WQNRO" }, "outputs": [ { "ename": "IndexError", "evalue": "list index out of range", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mIndexError\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[8]\u001b[39m\u001b[32m, line 2\u001b[39m\n\u001b[32m 1\u001b[39m numbers=[\u001b[32m1\u001b[39m,\u001b[32m2\u001b[39m,\u001b[32m3\u001b[39m,\u001b[32m4\u001b[39m]\n\u001b[32m----> \u001b[39m\u001b[32m2\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[43mnumbers\u001b[49m\u001b[43m[\u001b[49m\u001b[32;43m4\u001b[39;49m\u001b[43m]\u001b[49m) \u001b[38;5;66;03m# accessing non-existent index\u001b[39;00m\n\u001b[32m 3\u001b[39m \u001b[38;5;66;03m# numbers[4] would be the fifth item in this list, but this list has four items.\u001b[39;00m\n\u001b[32m 4\u001b[39m \u001b[38;5;66;03m# Hence, an error is generated\u001b[39;00m\n", "\u001b[31mIndexError\u001b[39m: list index out of range" ] } ], "source": [ "numbers=[1,2,3,4]\n", "print(numbers[4]) # accessing non-existent index\n", "# numbers[4] would be the fifth item in this list, but this list has four items.\n", "# Hence, an error is generated" ] }, { "cell_type": "markdown", "id": "409b3fcf", "metadata": { "id": "2dhKKWRViytg" }, "source": [ "### **Exercise: Indexing**\n", "In this exercise, you must access certain items within the lists that are provided. For each subquestion, you have to choose whether you want to use positive or negative indexing.\n", "\n", "Below is the list: `fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']`. Use both positive or negative indexing to access the following items within this list:\n", "\n", "1. The first item in the list.\n", "2. The second item in the list.\n", "3. The last item in the list.\n", "4. The third item from the end of the list." ] }, { "cell_type": "code", "execution_count": null, "id": "585a9801", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Krc1QtXapAGW", "outputId": "a3147b16-dc8a-42e6-b77b-b06a156732ab" }, "outputs": [], "source": [ "fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']\n", "\n", "# A) The first item\n", "first_item = # your code here\n", "print(\"First item:\", first_item)" ] }, { "cell_type": "code", "execution_count": null, "id": "95851d4e", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "sulp8XMCpAsd", "outputId": "f4578f24-67a2-4d5e-b414-d6c2b69c1714" }, "outputs": [], "source": [ "# B) The secon item\n", "second_item = # your code here\n", "print(\"Second item:\", second_item)" ] }, { "cell_type": "code", "execution_count": null, "id": "0df9dfd4", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "FFoilsLxpCF0", "outputId": "f3fd5a23-859e-4fe5-9ffe-2e1171d18504" }, "outputs": [], "source": [ "# C) The last item\n", "last_item = # your code here\n", "print(\"Last item:\", last_item)" ] }, { "cell_type": "code", "execution_count": null, "id": "000c68ac", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "g1HQqzYyi_P9", "outputId": "2fbf9ed1-6524-4c96-b071-34a5ccd3e317" }, "outputs": [], "source": [ "# D) The third item from the end\n", "third_from_end = # your code here\n", "print(\"Third item from the end:\", third_from_end)" ] }, { "cell_type": "markdown", "id": "58abd63a", "metadata": { "id": "0-UA-5RTn4CM" }, "source": [ "Given is the list: `pets`, consisting of three sublists which group categories of pets together. Use both positive or negative indexing to access the following items:\n", "\n", "5. The third sublist.\n", "6. The fourth item within the second sublist.\n", "7. The item called `Cat`. (**Optional**)\n", "\n", "💡 **Hint:** An element of a nested list like this one can be accessed using the same kind of indexing as with one-dimensional lists. However this time, you may need to index two values; i.e. the sublist and the item within that sublist. For instance, if you want to obtain the third sublist's second item, you write: `pets[2][1]`. (The 2 corresponds to the third sublist, and the 1 corresponds to the second item in this sublist.)" ] }, { "cell_type": "code", "execution_count": null, "id": "c36a2349", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "bg9ONDhypNF0", "outputId": "84294954-686f-4b5d-bbd8-03f4dda5a6e5" }, "outputs": [], "source": [ "pets = [['Dog', 'Cat'],\n", " ['Canary', 'Parrot', 'Cockatiel', 'Pigeon'],\n", " ['Goldfish', 'Axolotl', 'Turtle']]\n", "\n", "\n", "# E) The third sublist\n", "third_sublist = # your code here\n", "print(\"Aquatic Pets:\", third_sublist)" ] }, { "cell_type": "code", "execution_count": null, "id": "15336ab9", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "0Y7zNMcZpN0A", "outputId": "dbbc5710-d13a-4cf8-e2d4-1e06de55ab7b" }, "outputs": [], "source": [ "# F) The fourth item within the second sublist.\n", "fourth_item_second_sublist = # your code here\n", "print(\"A Common Bird Type:\", fourth_item_second_sublist)" ] }, { "cell_type": "code", "execution_count": null, "id": "1b3bd0a2", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "x3t8y_j-j3uW", "outputId": "cf6138b9-124c-4aa2-8bdc-25e51b764947" }, "outputs": [], "source": [ "# G) The item called Cat (Optional)\n", "item_cat = # your code here\n", "print(\"Your New Feline Friend:\", item_cat)" ] }, { "cell_type": "markdown", "id": "a58d120f", "metadata": { "id": "5PzlBBb6ptOR" }, "source": [ "-----------" ] }, { "cell_type": "markdown", "id": "bc1decef", "metadata": { "id": "EidFHaQKkooy" }, "source": [ "### **Exercise: Indexing of a 3x3 nested list**\n", "\n", "This exercise is split into three parts, designed to challenge you on the topic of nested lists.\n", "\n", "**Task 1:** Create a 3x3 matrix as a nested list, where each element is a single-digit number you may choose yourself.\n", "\n", "**Task 2a:** Let the program print the first element of the first column." ] }, { "cell_type": "code", "execution_count": null, "id": "01123a76", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "X1CyU26nlDn6", "outputId": "3cd0d640-d614-48ce-8d7a-88733fd42d49" }, "outputs": [], "source": [ "# Task 1: Creating a 3x3 matrix\n", "matrix = [[1, 2, 3],\n", " [4, 5, 6],\n", " [7, 8, 9]]\n", "\n", "# Task 2a: Print the first element of the first column\n", "# your code here" ] }, { "cell_type": "markdown", "id": "c027d37d", "metadata": { "id": "JsaGPAPdnA8O" }, "source": [ "**Task 2b:** Write a Python program that calculates and displays the sum of the elements along the main diagonal of the matrix (from the top-left to the bottom-right, i.e., 1+5+9)." ] }, { "cell_type": "code", "execution_count": null, "id": "151342b3", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Qw2gyf7wksjv", "outputId": "e05144a3-ce83-43c4-9481-624fbb59a7c7" }, "outputs": [], "source": [ "# Task 2b: Calculate the sum of main diagonal elements\n", "sum_main_diagonal = # your code here\n", "\n", "# Display the sum of main diagonal elements\n", "print(f\"Sum of main diagonal elements: {sum_main_diagonal}\")" ] }, { "cell_type": "markdown", "id": "866eb941", "metadata": { "id": "jXFGwzpqnEmq" }, "source": [ "**Task 3:** Write a Python program that calculates and displays the sum of the elements in the last column of the matrix." ] }, { "cell_type": "code", "execution_count": null, "id": "d88fa100", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "7xEOqErtkwqh", "outputId": "4ca44cd4-fe44-444c-d1c1-7c009b211054" }, "outputs": [], "source": [ "# Task 3: Calculate the sum of elements in the last column\n", "sum_last_column = # your code here\n", "\n", "# Display the sum of elements in the last column\n", "print(f\"Sum of elements in the last column: {sum_last_column}\")" ] }, { "cell_type": "markdown", "id": "764e2cbf", "metadata": { "id": "hexwsLeYponc" }, "source": [ "---------------" ] }, { "cell_type": "markdown", "id": "764f2e60", "metadata": { "id": "3iOzLcl28vBT" }, "source": [ "## List slicing\n", "We can call up a few items from a list in a sublist. This is called slicing. The correct syntax for doing this is __`[start:end:step]`__. This means you will get the items starting at __`start`__ index at every __`step`__$^{th}$ item until right before the __`end`__ index.\n", "\n", " **Note that the __`end`__$^{th}$ item will __*not*__ be included.** " ] }, { "cell_type": "code", "execution_count": null, "id": "ead63f4d", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ulcmZ5Lh_Fq3", "outputId": "25fe8297-ee1b-4f76-d9e1-4844d8953294" }, "outputs": [], "source": [ "numbers=[0,1,2,3,4,5,6]\n", "\n", "print(numbers[2:5:1]) # output: [2, 3, 4]\n", "print(numbers[2:5:2]) # output: [2, 4]\n", "print(numbers[-1:-5:-2]) # negative indexing, [6, 4]" ] }, { "cell_type": "markdown", "id": "9ab9c69b", "metadata": { "id": "UrIKlgP5Aacf" }, "source": [ "We can also skip some of the elements in the slicing syntax. Here is how they will be interpreted:\n", "\n", "|Syntax |Description|\n", "|-------------- |------- |\n", "|[start : end : step]|from `start` to `end-1` with step `step`|\n", "|[start : end] | step=1 |\n", "|[start : : step]| end = last index \t | \n", "|[ : end : step] | start=0, first index|\n", "|[ : ] | all elements in the list with step=1|" ] }, { "cell_type": "code", "execution_count": null, "id": "726fb486", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Vty9G3NoCEgj", "outputId": "61df0192-4e14-41a7-efbc-a6f9575f6b69" }, "outputs": [], "source": [ "numbers=[0,1,2,3,4,5,6]\n", "print(numbers[2:5])" ] }, { "cell_type": "code", "execution_count": null, "id": "1256bedb", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "aEkvqFCHmDrV", "outputId": "96c0b910-c3c6-4331-829c-63ccdb9f9ccd" }, "outputs": [], "source": [ "print(numbers[:3]) # start=0, end=3, step =1" ] }, { "cell_type": "code", "execution_count": null, "id": "7a44ff23", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "SmqVeoTbmI_o", "outputId": "66a3fba1-ba8c-4a32-9957-2f775a06e472" }, "outputs": [], "source": [ "print(numbers[1::2]) # start=1, end= last, step =2" ] }, { "cell_type": "code", "execution_count": null, "id": "ab5b351f", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "IjjCR9YPmGpc", "outputId": "4bf4d8e1-a74e-4000-f150-006acc91ecb3" }, "outputs": [], "source": [ "print(numbers[-5:]) # negative indexing, start=-5, end= last, step =1" ] }, { "cell_type": "code", "execution_count": null, "id": "6a5d2030", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "pOJXsiwFmFeX", "outputId": "565c48a0-ba42-4576-a332-b6bcde1eda29" }, "outputs": [], "source": [ "print(numbers[::-1]) # negative steps, start=last, end=0, step =-1" ] }, { "cell_type": "markdown", "id": "8baf4533", "metadata": { "id": "qw9IuvSNeRsZ" }, "source": [ "### **Exercise: Sublist extraction**\n", "\n", "Given below is the main list `count_to_ten`. In this exercise, you must use list slicing to create and print the new lists called `count_down`, `even_numbers` and `sublist` as described below. **Note that you may only do this by extracting sublists from the main list.**\n", "\n", "1. Create and print a new list named `count_down` containing elements from 10 to 1.\n", "2. Create and print a new list named `even_numbers` containing only the even integers from `count_to_ten`.\n", "3. Create and print a new list named `sublist` by extracting the sublist [5, 10] from the `count_to_ten` list." ] }, { "cell_type": "code", "execution_count": null, "id": "b631142e", "metadata": { "id": "-y7V25O0emhJ" }, "outputs": [], "source": [ "# Initialise your main list first:\n", "count_to_ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" ] }, { "cell_type": "code", "execution_count": null, "id": "8a555be2", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "qZR8j-LMqTaZ", "outputId": "7e547fc0-778f-4fe3-959c-a452bedab7ce" }, "outputs": [], "source": [ "# A) Elements from 10 to 1\n", "count_down = # your code here\n", "print(f\"Count Down List: {count_down}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "c276ba15", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "0bA5nAWLqVQe", "outputId": "c4e2ca5a-bbfa-4dba-f4fc-6e389b52fa13" }, "outputs": [], "source": [ "# B) Even integers from count_to_ten\n", "even_numbers = # your code here\n", "print(f\"Even Integer List: {even_numbers}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "209629bb", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "b5g8FsBWqafT", "outputId": "1b54c863-5ae0-4460-9511-0b0d923f2139" }, "outputs": [], "source": [ "# C) Sublist [5, 10] from count_to_ten\n", "specific_indexes = # your code here\n", "print(f\"Specific Indexes Sublist: {specific_indexes}\")" ] }, { "cell_type": "markdown", "id": "48535ca6", "metadata": { "id": "_xi3G3lfpmH1" }, "source": [ "---------" ] }, { "cell_type": "markdown", "id": "b72f990b", "metadata": { "id": "YYlDHUjm3dR3" }, "source": [ "## Modifying items (reassigning values) in a list\n", "\n", "You can modify an item in a list simply by using `list[index] = `. However, you need to access that item using correct list indexing. Here is an example where two items in a list are modified:" ] }, { "cell_type": "code", "execution_count": null, "id": "febbc5e2", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "vrlQhk8H3x52", "outputId": "d016e9b1-b9c1-4733-888a-0ac3a2ee5357" }, "outputs": [], "source": [ "numbers=[0,1,2,3,4,5,6]\n", "\n", "# to modify the first item with value \"Zero\"\n", "numbers[0] = \"Zero\"\n", "\n", "# to modify the third item with value \"Two\"\n", "numbers[2] = \"Two\"\n", "print(numbers)" ] }, { "cell_type": "markdown", "id": "ae9a5a9e", "metadata": { "id": "QjkzoccbhIPk" }, "source": [ "To modify multiple items simultaneously, you can use list slicing:" ] }, { "cell_type": "code", "execution_count": null, "id": "c15d63e1", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "EmNIyCVcg04j", "outputId": "88074bbb-878a-4157-a948-7fbb48a6adec" }, "outputs": [], "source": [ "# to modify multiple items\n", "numbers[4:7]=[\"Four\",\"Five\",\"Six\"]\n", "print(numbers)" ] }, { "cell_type": "markdown", "id": "fd63fd04", "metadata": { "id": "r1rmEVShGmW2" }, "source": [ "**Attention:** Be very careful with indexing! Below is what happens if you use a wrong indexing compared to what you have in mind. It doesn't give an error but provides different results than intended." ] }, { "cell_type": "code", "execution_count": null, "id": "d5140747", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "y_9rTLuGtbRk", "outputId": "90839c65-34e3-4203-cf18-d3e5ce9d8ad0" }, "outputs": [], "source": [ "# example 1: adding one extra item for not using the correct end step\n", "numbers=[0,1,2,3,4,5,6]\n", "numbers[3:5]=[\"Three\",\"Four\",\"Five\"]\n", "print(numbers)" ] }, { "cell_type": "code", "execution_count": null, "id": "ab4d76a3", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "zUbYdgzjGdnU", "outputId": "121dd96a-8a6f-42a8-95ae-ec3830d2529d" }, "outputs": [], "source": [ "# example 2: creating nested lists\n", "numbers=[0,1,2,3,4,5,6]\n", "numbers[3]=[\"Three\",\"Four\",\"Five\"]\n", "print(numbers)" ] }, { "cell_type": "markdown", "id": "ba5c0f25", "metadata": { "id": "89_5nNMG77yP" }, "source": [ "## Removing an item from a list\n", "To remove an item you can use the `del` statement. Here is a quick example:" ] }, { "cell_type": "code", "execution_count": null, "id": "426455b9", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "d0xzeZW136si", "outputId": "7947308f-5afa-4532-f861-b7cb5a48b0c0" }, "outputs": [], "source": [ "numbers=[0,1,2,3,4,5,6]\n", "del numbers[4:]\n", "print(numbers)" ] }, { "cell_type": "markdown", "id": "025cabc6", "metadata": { "id": "oD6vniOp2vGf" }, "source": [ "### **Exercise: Del statement (Optional)**\n", "\n", "Given is the list `potential_snacks`, containing the snacks you plan on buying for a movie night you are hosting. However, you come to realise one of your guests has a peanut allergy and another one is allergic to chocolate. Hence, you want to update your list by doing the following:\n", "\n", "**Remove `Peanuts` and `Chocolate Bars` from your list of potential snacks using the `del` statement.**" ] }, { "cell_type": "code", "execution_count": null, "id": "afa9f366", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "5sbTmpFN2oX6", "outputId": "d300a7a4-97ef-40f1-e040-db36f7d6c1c5" }, "outputs": [], "source": [ "potential_snacks = ['Chips', 'Peanuts', 'Chocolate Bars', 'Cookies', 'Mochi']\n", "\n", "# Your code here\n", "\n", "print(f\"The Snacks You Can Still Buy Are: \\n {potential_snacks}\")" ] }, { "cell_type": "markdown", "id": "30d43853", "metadata": { "id": "6sR6X6gipjh0" }, "source": [ "_____________" ] }, { "cell_type": "markdown", "id": "cd7ab6b0", "metadata": { "id": "LmXGIbZlKJyQ" }, "source": [ "## Python list methods\n", "\n", "Here is a list of built-in operations and methods you can perform on lists. It's good enough for now to know that these operations exist and that you can use them. If you need them later, you can search online for the correct syntax and examples.\n", "\n", "|Syntax |Description|\n", "|-------------- |------- |\n", "|+ | concatenate (join) two lists |\n", "|*| multiply a list\t | \n", "|append() | add a new element at the end of the list|\n", "|extend() | add multiple elements at the end of the list|\n", "|insert()| insert elements at given indexes|\n", "|remove()| remove an element from the list (only the first occurrence)|\n", "|pop()| remove an element using its index|\n", "|Reverse()| reverse the elements|\n", "|len() | length of the list|\n", "|count() |count the number of occurences of an element|\n", "|sort() | sort the elements |\n", "|clear() | clear the list |" ] }, { "cell_type": "markdown", "id": "527896a6", "metadata": { "id": "oLCFdbeV3atK" }, "source": [ "### **Exercise: Shopping list**\n", "\n", "Start by creating a list called `shopping_list` with the items: \"Apples\", \"Milk\", \"Bread\", \"Eggs\", and then perform the following operations on it:\n", "\n", "1. Using `append` to add \"Butter\" to the list.\n", "2. Remove \"Bread\" from the list.\n", "3. Create a new list called `special_offers` with the items: \"Chips (50% off)\", \"Soda (25% off)\".\n", "4. Using `append` add the `special_offers` list to the shopping list.\n", "5. Print the length of the list to see how many items it has." ] }, { "cell_type": "code", "execution_count": null, "id": "8eb762cb", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "11D_9pFTsJdd", "outputId": "bdea2b54-8d31-4bff-e05d-f1fc7c8ab1ea" }, "outputs": [], "source": [ "# Initialising the list:\n", "shopping_list = # your code here\n", "\n", "# A) Add \"Butter\" to the list.\n", "shopping_list.append(# your code here)\n", "print(f\"A) Shopping List With Butter Added: {shopping_list}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "c3ac6c4a", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "9oPjrMc_u8ua", "outputId": "04a838e5-49c7-4d45-c366-669b8c9c523e" }, "outputs": [], "source": [ "# B) Remove \"Bread\" from the list.\n", "# your code here\n", "print(f\"B) Shopping List With Bread Removed: {shopping_list}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "b5d49e8b", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "dYUXFom-sOwl", "outputId": "816d68b1-fb99-4aeb-8d01-29ff4343e75f" }, "outputs": [], "source": [ "# Initialising the list again after A) and B) have been performed\n", "shopping_list = [\"Apples\", \"Milk\", \"Eggs\", \"Butter\"]\n", "\n", "# C) Create a new list called \"special_offers\"\n", "# This list contains the following items: \"Chips (50% off)\", \"Soda (25% off)\".\n", "special_offers = # your code here\n", "print(f\"C) Special Offers: {special_offers}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "2f323f80", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "1330HNZ1sP1k", "outputId": "d18c9b54-ba0a-4157-a670-785ef928e23d" }, "outputs": [], "source": [ "# D) Add \"special_offers\" to the shopping list.\n", "# your code here\n", "print(f\"D) Shopping List and Special Offers: {shopping_list}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "1cf058e1", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "gmqHPx_NvFYJ", "outputId": "d6e69ec1-725b-49b3-eaad-512c70058d91" }, "outputs": [], "source": [ "# E) Print the length of the shopping list\n", "# your code here" ] }, { "cell_type": "markdown", "id": "9eab2034", "metadata": { "id": "qHHjvF19pxKO" }, "source": [ "-------" ] }, { "cell_type": "markdown", "id": "72b24da1", "metadata": { "id": "SsQ7BTIj-J-6" }, "source": [ "### **Summarising Exercise: Extensive list manipulation**\n", "\n", "This exercise will use a bit of everything you have learned so far to make a list of your liking. You can create a list with items you may choose yourself and then you must perform the following operations on it:\n", "\n", "1. Start by creating `my_list` (containing four items).\n", "2. Print the first item in your list.\n", "3. Delete the fourth item in your list.\n", "4. Append two new (separate) items to your main list. Again, you may name these two items as you please.\n", "5. Change the second and third item in your list to something else. (An example would be changing the second item to 'Hermit Purple' and the third item to 'Hierophant Green'.)\n", "6. Lastly, reverse all items in your list." ] }, { "cell_type": "code", "execution_count": null, "id": "91141f73", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "CSLzRb9CsWP8", "outputId": "ffb81974-97a8-42c0-9a33-56e8201e8b76" }, "outputs": [], "source": [ "# A) Create your list of four items\n", "my_list = # your code here\n", "print(f\"A: {my_list} \\n\")" ] }, { "cell_type": "code", "execution_count": null, "id": "83adfecd", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Xo_-nX8hsXQJ", "outputId": "620950be-8406-4f66-b593-fe2980abaf2a" }, "outputs": [], "source": [ "# B) Print the first item\n", "first_item = # your code here\n", "print(f\"B: {first_item }\")" ] }, { "cell_type": "code", "execution_count": null, "id": "d4264431", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "LONA7HLBsXMp", "outputId": "ec3611f9-47a3-4336-e69b-002ddf63d2d0" }, "outputs": [], "source": [ "# C) Delete the fourth item\n", "del # your code here\n", "print(f\"C: {my_list}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "91bd6153", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "6w6FJMv3sXJt", "outputId": "f8beaaab-da98-4f8e-a8da-934ce9e6d94e" }, "outputs": [], "source": [ "# D) Append two new (separate) items\n", "my_list.append(# your code here)\n", "my_list.append(# your code here)\n", "print(f\"D: {my_list}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "f8426664", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "B_3gK4rUsXGB", "outputId": "e3db7ee7-7f32-40fe-b573-12d266e0080e" }, "outputs": [], "source": [ "# E) Change 2nd and 3rd item\n", "# your code here\n", "print(f\"E: {my_list}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "81b75c16", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "DTAKWqzZ-8ZC", "outputId": "1b829fec-db94-44df-a160-de6f5a6fedc6" }, "outputs": [], "source": [ "# F) Reverse your list\n", "# your code here\n", "print(f\"F: {my_list}\")" ] } ], "metadata": { "jupytext": { "text_representation": { "extension": ".md", "format_name": "myst", "format_version": 0.13, "jupytext_version": "1.16.4" } }, "kernelspec": { "display_name": "Python 3", "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.11" }, "source_map": [ 13, 19, 26, 40, 51, 68, 79, 90, 101, 112, 123, 132, 145, 159, 171, 183, 195, 205, 222, 234, 246, 250, 260, 276, 280, 294, 298, 312, 316, 323, 337, 349, 360, 370, 380, 390, 400, 410, 417, 429, 441, 453, 457, 463, 480, 484, 496, 500, 513, 526, 531, 543, 551, 565, 569, 590, 602, 617, 629, 645, 657, 668, 672, 685, 697, 709, 721, 734, 746 ] }, "nbformat": 4, "nbformat_minor": 5 }