{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists I\n", "\n", "Until now, you have only used numbers and booleans as data to compute with in this course. Numbers are indeed very useful, but sometimes we need to have data in a more structured way. Data structures serve this purpose. Today we look at one of the simplest, and yet most pervasive, data structures out there: **lists**.\n", "\n", "Lists are... well... lists.\n", "\n", "Lists can have anything inside: `int`, `float`, `boolean`, and other lists! \n", "This is how we write a list in Python:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[11, 12, 13], [21, 22, 23], [31, 32, 33]]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# List of ints\n", "[3,2,4,7,2]\n", "\n", "# Lists of floats\n", "[1.2, 4.6, 3.0]\n", "\n", "# Lists of booleans\n", "[True, False, False]\n", "\n", "# Lists of lists of ints\n", "[ [11,12,13],\n", " [21,22,23],\n", " [31,32,33] ]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lists can be heterogeneous as well (*this is a python particularity*)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[True, 4, 3.2, [1, 4, 5]]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[True, 4, 3.2, [1,4,5]]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Accessing elements and chunks\n", "\n", "Elements in a list an be found by their *index*, the position they are in the list. By convention, indices start on the left and the first index is 0. We can get an element at position `i` by using brackets:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L = [4,5,3,6,2]\n", "L[2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is possible to access sublists of a list, by indexing with two values, a start and end index, separated by a colon. If `L` is a list, `L[i:j]` results in the sublist starting at position `i` and ending at position `j-1` (just like `range`).\n", "\n", "This is called *slicing*." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 3, 4]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L = [0,1,2,3,4,5,6]\n", "L[2:5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Speaking of `range`, we can also get a sublist by skipping some elements by `k` steps." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 3, 5, 7]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L = [0,1,2,3,4,5,6,7,8,9]\n", "L[1:8:2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Slicing can be abbreviated if:\n", "- We are starting from 0: `L[:4]` is the same as `L[0:4]`\n", "- We are going until the end: `L[1:]` is the list `L` without the first element.\n", " \n", "Slicing with steps can also be abbreviated:\n", "- `L[3::2]` starting from element at index 3 until the end, step by 2\n", "- `L[:10:3]` starting from 0 until the tenth element, take every third\n", "- `L[::2]` take very second element" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### List length\n", "\n", "The length of a list can be obtained using the function `len` on the list." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "11" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L = [0,1,2,3,4,5,6,7,8,9,10]\n", "n = len(L)\n", "n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Finding elements\n", "\n", "Can you write a function `def find(L, e)` that returns `True` if element `e` is in the list `L`, and returns `False` otherwise?" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def find(L, e):\n", " # Complete me\n", " return True" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Of course you can!\n", "But this is such a common operations, that python has it built-in for you. \n", "\n", "Checking whether an element is inside a list can be done using the `in` or `not in` operations, which return `True` or `False` (meaning they can be used as conditions for `if`, `elif`, or `while` loops)." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L = [4,2,5,6,1,7,8]\n", "5 in L" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 not in L" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Modifying a list\n", "\n", "We have seen ways to access a list, now it is time to modify it.\n", "\n", "Particular positions of a list can be modified by using a simple assignment, but having the list with the proper index on the left side of `=`" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 5, 1, 1, 2]" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L = [1,5,1,1,0]\n", "L[4] = 2\n", "L" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Adding elements to a list\n", "\n", "Lists can be concatenated with each other via the `+` operator:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4]" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L1 = [1,2]\n", "L2 = [3,4]\n", "L1 + L2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this case, adding one element `e` to a list, at the end or the beginning, can be done by creating a list with only `e` inside, and concatenating this list:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 0]" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L = [1,2,3]\n", "L + [0]" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2, 3]" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[0] + L" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using slicing, we can add elements at arbitrary positions of a list:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[6, 6, 0, 6, 6]" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "L = [6,6,6,6]\n", "L[:2] + [0] + L[2:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Looping through lists\n", "\n", "Most of the problems involving lists will requires some sort of loop. Most likely, you will need to loop through the elements of the list to do something with each one of them.\n", "\n", "The main way of looping through a list is by taking its length, and building a range with that:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "i = 0 L[i] = 10\n", "i = 1 L[i] = 20\n", "i = 2 L[i] = 30\n", "i = 3 L[i] = 40\n", "i = 4 L[i] = 50\n" ] } ], "source": [ "L = [10,20,30,40,50]\n", "n = len(L)\n", "\n", "for i in range(n):\n", " # Prints the values at each iteration\n", " print(\"i =\", i, \" L[i] =\", L[i])\n", " \n", " # Takes the element at position i\n", " e = L[i]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you decide that you do not need the indices inside the loop, but only the elements of the list, a more consise loop is:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "e = 10\n", "e = 20\n", "e = 30\n", "e = 40\n", "e = 50\n" ] } ], "source": [ "L = [10,20,30,40,50]\n", "\n", "for e in L:\n", " print(\"e =\", e)\n", " # You only have access to the element, not the index" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We **strongly** suggest that you stick with the first option in the beginning." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tuples\n", "\n", "Tuples behave exactly like lists, except that they have fixed size and can never be modified (that means, we cannot modify one element at a specific position). You have used tuples in the course without noticing: when you had to return two values for a function, we asked you to return it as `(value1, value2)`. Well, you returned a tuple!" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "T = (1,2,3,4)\n", "T[1]" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(2, 3)" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "T[1:3]" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(2, 3, 4)" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "T[1:]" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 3, 4, 5, 6)" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "T = T + (5,6)\n", "T" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 0\n", "\n", "Implement the function `times10(L)` that returns a list containing the same elements as `L`, but multiplied by 10.\n", "\n", "For example, `times10([1,2,3])` should return `[12,20,30]`." ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def times10(L):\n", " return []" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 1\n", "\n", "Find the maximum element of a list." ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def max(L):\n", " return 42" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 2\n", "\n", "You receive a list with zeros and ones corresponding to a binary number. Write the function `binToDec(B)` that returns the decimal representation of `B`. \n", "\n", "For example, `binToDec([1,1,0])` should return 6." ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def binToDec(B):\n", " return 42" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 3\n", "\n", "Given a list `L` and element `e`, write the function `count(L, e)` that counts the number of times `e` occurs in `L`." ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def count(L, e):\n", " return 42" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 4\n", "\n", "Implement the function `allTheSame(L)` that returns `True` if all elements of list `L` are the same, and `False` otherwise." ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def allTheSame(L):\n", " return True" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.8.3" } }, "nbformat": 4, "nbformat_minor": 2 }