{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lists\n", "\n", "## Basic Idea\n", "The primary variables we have seen so far have all been single values\n", "(regardless of their type),\n", "e.g. a single string, single number, or single boolean.\n", "Very often, it is helpful to do more than just a single computation, but\n", "instead perform a computation across (or on) a large amount of data,\n", "requiring *data structures* - objects specifically designed to store and\n", "organize multiple pieces of data. \n", "\n", "One data structure available in Python\n", "is a *list*: an ordered, mutable collection of objects. *Mutable* refers\n", "to the fact that the contents of the list can be changed. \n", "\n", "Lists in Python\n", "can contain any type of object including strings, numerical types, booleans,\n", "and other lists (along with other objects we have not yet talked about).\n", "The have no set size (in contrast to many other languages) and it is\n", "possible to add and remove things as desired. \n", "\n", "### List Creation\n", "We've already seen one example of a list when discussing for loops. Recall\n", "that lists are defined in Python by listing the elements inside `[]`.\n", "For example, we could create a list of strings of color names:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "colors = ['orange', 'red', 'green', 'blue', 'yellow']\n", "print(colors)\n", "print(type(colors))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lists are not limited to strings, however; we could also have a list with\n", "numerical values:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "heights = [67, 62.5, 69, 71, 72.5, 75]\n", "print(heights)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that the previous list contains both `float` and `int` values. We could\n", "also have a list with an even wider range of types. For example, the following\n", "list has an `int` for its first element, a `str` for its second element, another\n", "list as its 3rd element, and a `bool` as its fourth element." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mixed_list = [10, \"lays bbq\", [3.99, 4.49, 2.99], True]\n", "print(mixed_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note\n", "that `list()` is a function to convert other types to a list, so you should\n", "not use `list` as a variable name (a very common mistake)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Creating and Adding to Lists\n", "The previous lists were all initially created with all of their elements.\n", "It's also possible (and common) to create an empty list and add elements\n", "as desired. To create an empty list, we simply set the desired variable\n", "name to empty brackets, e.g.," ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "countries = []" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then, we can add items to the list via the `append()` method. Note, this is a *method*,\n", "not a function. Recall that a function is a named block of code. A *method*, while\n", "similar, is tied to a specific object, so in order to call it we preceed the method\n", "name by the variable name for the object we are invoking it with, e.g. `variablename.methodname()`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "countries.append('Italy')\n", "countries.append('Mexico')\n", "countries.append('Canada')\n", "countries.append('USA')\n", "countries.append('South Africa')\n", "countries.append('Greece')\n", "countries.append('Spain')\n", "print(countries)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using the `append()` method to add to a list isn't limited to lists\n", "that were initially created as empty, we can append to any list regardless\n", "of how it was created.\n", "\n", "#### List from Range\n", "\n", "Often, we wish to create a list populated with a range of numbers.\n", "Recall the `range(start, stop, step=1)` function used\n", "to loop through a preset range of values. To create a list with the\n", "values in this range, we can typecast the result of range to a list with\n", "the function `list()` (like we could convert from a string to a float).\n", "For instance, suppose we want a list with the numbers 1 through 10:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "numbers = list(range(1,11))\n", "print(numbers)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### List Operations\n", "\n", "#### Checking if Element in List\n", "One common operation we need to perform is to see if an item exists in\n", "a list. In Python, we do that via the `in` reserved word, e.g.\n", "`val in listname`, which evaluates to `True` or `False`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Spain\" in countries)\n", "print(\"Australia\" in countries)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "More often than not, we would not choose to `print` the result of\n", "this check, but instead utilize this check as the condition for an `if`\n", "statement to control what occurs when the element is present in the list." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Concatenation\n", "\n", "Another very common operation is *concatenation*, where the elements\n", "of two lists are combined, one after another. In Python, the `+`\n", "operator performs concatenation when applied to lists." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list1 = [-1,0,1]\n", "list2 = [2,3,4]\n", "list3 = list1 + list2\n", "print(list1)\n", "print(list2)\n", "print(list3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Repetition\n", "\n", "In addition to the `+` operator, the `*` operator is also defined\n", "for lists. When we multiply a list by an integer, it is used to\n", "repeat the list a specified number of times. This follows from\n", "the use of `+` as concatenation and the \n", "general definition of multiplication where it is simply adding (concatenating)\n", "the list to itself a specified number of times. For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "repeated = list1*3\n", "print(repeated)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Accessing List Items\n", "\n", "### Indexing\n", "\n", "To access individual elements in a list, we use the square brackets, `[]` with the index\n", "number of the desired element inside. Python lists are indexed starting at 0, so the 1st\n", "element has index 0, 2nd element has index 1, and so on. Note, that because indexing starts\n", "at 0, the index of the last item is the one less than the length of the list.\n", "\n", "For example, consider the list of countries above:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(countries)\n", "print(countries[0])\n", "print(countries[1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also use the index notation to set a specific element (rather than just access it),\n", "which changes the underlying list." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "countries[2] = 'Argentina'\n", "print(countries)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition to positive indices (which start at 0 with the beginning of the list),\n", "Python also allows you to use negative indices, which work from the back of the list\n", "where `[-1]` is the last item, `[-2]` is the 2nd to last item, etc. This\n", "is a particularly useful feature of Python that can be very handy depending on what\n", "you are attempting to accomplish." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(countries[-1])\n", "print(countries[-2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Lists of Lists\n", "This indexing only applies to the outermost list level. Suppose we have \n", "a list where each element is itself another list. Then, this indexing notation\n", "will give another list, which we would then need to index into with another index.\n", "For example," ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cities = [[\"Grand Rapids\", \"Detroit\", \"Traverse City\"],\n", " [\"Chicago\", \"Urbana-Champaign\", \"Peoria\"],\n", " [\"San Diego\", \"San Francisco\", \"Los Angeles\", \"Santa Barbara\"]]\n", "print(cities[2])\n", "ca = cities[2]\n", "print(ca[1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the above, we explicitly stored the inner list before indexing into it,\n", "but that's not necessary, we can provide multiple indices by using multiple\n", "sets of square brackets, e.g., `[][]`. For example, the above could have\n", "simply been:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(cities[2][1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first index applies to the outermost list, the 2nd index into the inner list. Note\n", "in this example that not all inner lists are of the same length.\n", "It's also possible to have more than 2 levels of nested lists as well,\n", "and there are times where 3 or 4 levels of nested lists are the most natural choices.\n", "Regardless, from left-to-right the square brackets index to from outer most to inner most\n", "lists." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Slicing\n", "\n", "Often, we wish to do more than access a single list element, and instead\n", "want to extract some sublist of the items in the list. This is\n", "known as *slicing*. In Python, slicing creates a copy of the list\n", "with a specified set of the elements from the original list. We still\n", "use the bracket notation, but instead of using a single index, we give\n", "it multiple indices to denote the start and stop index for the slice,\n", "separated by a colon:\n", "```\n", "listname[start:stop]\n", "```\n", "The slice starts at index `start` (inclusive)\n", "and goes up to, but not including `stop` (exclusive). In addition\n", "to `start` and `stop`, we can also optionally provide a `stride`\n", "(also separated by a colon):\n", "```\n", "lstname[start:stop:stride]\n", "```\n", "which indicates how much the index should go up by between for each\n", "consecutive element selected. The default value for `stride` is 1,\n", "which indicates to get all indices." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(countries[1:4])\n", "print(countries[1:4:2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All three values (`start`, `stop`, and `stride`) can be negative.\n", "* negative `start` or `stop` -> just a negative index\n", "* negative `stride` -> go in reverse from end to front" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(countries)\n", "print(countries[-2:0:-1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Additionally, either (or both) `start` and `stop` can be left empty:\n", "* empty `start` -> start at the beginning\n", "* empty `end` -> go until very end" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"all but first =\", countries[1:])\n", "print(\"all but last =\", countries[:-1])\n", "print(\"reversed =\", countries[::-1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists and Loops\n", "\n", "We've previously seen one example of how a for loop can be\n", "used to loop through the items in a list\n", "```\n", "for val in lst:\n", " # some code using val\n", "```\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "tv_shows = [\"the big bang theory\", \"the good place\", \"mandalorian\", \"great british baking show\"]\n", "for show in tv_shows:\n", " print(show)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If all we need are the values in the list, this\n", "style of loop is a great choice. However, there\n", "are times where we need the list indices in addition to the\n", "list entries. For example, we may need to update the element\n", "of the list or need to get a corresponding entry in another list.\n", "We can do this by using a for loop with `range`, but combining it with\n", "the built-in function `len`. Recall that the function `len` can be used\n", "to get the length of a string, it can also be used to get the number\n", "of elements in a list.\n", "\n", "For instance, suppose we want to edit an existing list of numbers to contain\n", "the squares of the numbers:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nums = [-2, 1, 2, 4]\n", "for i in range(len(nums)):\n", " nums[i] = nums[i]**2\n", "\n", "print(nums)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### List Comprehension\n", "\n", "We can also utilize `for` loops to create or fill lists.\n", "Suppose we wish to fill a list with the squares of all of the numbers\n", "up to 6. We could use a for loop to loop through the values $0, 1, \\ldots, 6$\n", "and append the square of the loop variable to a list, which is completely valid." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lstA = []\n", "for i in range(7):\n", " lstA.append(i**2)\n", "print(lstA)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, there is also a short-hand way of accomplishing this same task known\n", "as *list comprehension*. It does not fundamentally provide any additional\n", "capability, but it is considered a \"pythonic\" way of doing things and you'll\n", "likely come across it at some point in code." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lstB = [x**2 for x in range(7)]\n", "print(lstB)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This list comprehension can also be combined with conditionals. For instance, maybe we want all of the squares that are odd:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lstC = [x**2 for x in range(7) if x%2 == 1]\n", "print(lstC)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions and Methods with Lists\n", "\n", "### Functions\n", "We've seen already how one of the built-in functions, `len`, can be\n", "applied to lists. A few other commonly used built-in functions can\n", "be applied to lists as well. Note, as these are all functions, the list\n", "is passed in as an argument to the function.\n", "\n", "* `len(lstname)` -> returns the number of elements in the list\n", "* `sum(lstname)` -> returns the sum of the elements in the list\n", "* `max(lstname)` -> returns the maximum of the elements in the list\n", "* `min(lstname)` -> returns the minimum of the elements in the list" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "counts = [30, 25, 10, 14, 6]\n", "print(\"number of elements =\", len(counts))\n", "print(\"sum =\", sum(counts))\n", "print(\"min =\", min(counts))\n", "print(\"max =\", max(counts))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### List Methods\n", "\n", "While the functions are general built-in functions that can be applied in\n", "multiple ways (for instance to get the length of a string or to compute the\n", "max of 2 values), there are also operations specific to lists, often an individual\n", "list. These are *methods* associated with the specific object and are called by \n", "`lstname.methodname(args)`. The full list\n", "of methods for python lists is available in the\n", "[documentation](https://docs.python.org/3/tutorial/datastructures.html), but\n", "some of the most commonly used methods are:\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Adding to Lists\n", "\n", "* `append(x)` -> add item `x` to the end of the list\n", "* `insert(i, x)` -> insert item `x` at index `i`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "names = [\"Matt\",\"Luke\", \"Julia\", \"Miles\", \"Alice\", \"Paul\", \"Matt\", \"Mia\"]\n", "names.insert(1, \"Michelle\")\n", "print(names)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Removing from Lists\n", "\n", "* `pop(i)` -> remove the item at index `i` in the list and return it (`i` is optional, default\n", " is to remove and return the last item in the list)\n", "* `remove(x)` -> remove the first item with value equal to `x`. Raises a `ValueError` if no\n", " item equal to `x` exists in the list." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "removed = names.pop(3)\n", "names.remove(\"Luke\")\n", "print(names)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Miscellaneous\n", "\n", "* `index(x)` -> returns the index of first item with value equal to `x` . Raises a `ValueError`\n", " if no item equal to `x` exists in the list. Can optionally pass a `start` and `end`,\n", " to specify subsequence of list in which to search for `x`.\n", "* `sort()` -> sort the list *in place*. This means that it does not return a new list, but modifies\n", " the original list to be sorted. \n", "* `count(x)` -> return the number of times `x` occurs in the list\n", "* `copy()` -> return a copy of the list" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "location = names.index(\"Mia\")\n", "print(location)\n", "\n", "names.sort()\n", "print(names)\n", "\n", "print(names.count(\"Matt\"))\n", "\n", "names2 = names.copy()\n", "names.append(\"Jill\")\n", "print(names)\n", "print(names2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## More About Lists\n", "\n", "### References\n", "\n", "We previously talked about lists in python, including\n", "how to create them, how to traverse them, and the methods\n", "lists have available. Technically everything in python is\n", "an *object*. Objects can have both data and methods associated\n", "with them. When we have objects, the actual variable name is not actually the\n", "object itself, but instead a *reference* to the underlying spot\n", "in memory where the computer stores the object.\n", "\n", "We can check in python if 2 variables refer to the same object\n", "with `is`. This test is far stronger than equality, it tests if\n", "they actually point to the same underlying object. We can use the\n", "`id()` function to get an identifier for an object, unique for\n", "each object. These allow us to see when 2 variable names actually\n", "point to the same underlying object" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 1\n", "b = a\n", "print(id(a), id(b), a is b)\n", "b = 2\n", "print(id(a), id(b), a is b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Who Cares?\n", "\n", "You are likely wondering to yourself why any of this matters.\n", "Who actually cares if 2 variables reference the same\n", "underlying object or not? For basic types, such as `float`,\n", "`int`, `bool`, and `str`, you are right to wonder -- there's really\n", "no purpose because the underlying object never changes.\n", "That's what we saw in the previous code example: originally\n", "both `a` and `b` referred to the same underlying object. However,\n", "when we set `b = 2`, it actually created a new underlying object\n", "with the value of 2 and then set the variable `b` to refer\n", "to that new underlying object. This happened because `int` types\n", "are *immutable* -- they cannot be changed. \n", "\n", "Recall, however, that lists are *mutable*, meaning the underlying\n", "object can actually be changed. Let's consider what this\n", "means by looking at the following code:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lsta = [10,12,14]\n", "lstb = lsta\n", "print(lsta)\n", "print(lstb)\n", "print(id(lsta), id(lstb), lsta is lstb)\n", "lstb[0] = 8\n", "print(lsta)\n", "print(lstb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The line `lstb = lsta` assigns `lstb` to refer to the\n", "same spot in memory as `lsta`.\n", "Because of this, when we modified the first element of `lstb`,\n", "the first element of `lsta` changed as well. This occurred\n", "because they both reference the same spot in memory,\n", "and this underlying spot in memory is actually what is changed.\n", "\n", "This means that you have to be more careful with lists (and other\n", "mutable types that we haven't yet talked about because modifying\n", "the object can have wider impacts than you may expect at first)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### References with Functions\n", "\n", "In addition to being careful in general with mutable types,\n", "we also need to be very careful when passing mutable objects\n", "as arguments to functions. Why? When passing a variable\n", "as an argument to a function in python, only the reference\n", "is copied, not the underlying memory. This causes any edits\n", "made inside the function to the list to modify the list outside\n", "of the function as well.\n", "\n", "To see this effect, consider the following 2 functions:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def foo(val1, val2):\n", " val1 = val1*2\n", " val2 = val2*2\n", "\n", "c = 3\n", "d = 4\n", "foo(c,d)\n", "print(c, d)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def bar(lst1, lst2):\n", " lst1[0] = \"it changed\"\n", " lst2 = [7,8,9]\n", "\n", "alist = [1,2,3]\n", "blist = [4,5,6]\n", "bar(alist, blist)\n", "print(alist)\n", "print(blist)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that even though `val1` and `val2` were modified\n", "inside `foo`, `c` and `d` outside the function\n", "remained unchanged. However, in the second code block,\n", "when `lst1` inside `bar` was modified, it actually\n", "modified `alist` which was passed in for that parameter.\n", "However, because `lst2` was set to a new list in `bar`,\n", "it just modified the reference (which was copied), not\n", "the underlying list, so `blist` remained unchanged." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Special Functions with Lists - Revisiting Random Numbers\n", "\n", "We looked previously at how we could use the\n", "[`random` module](https://docs.python.org/3/library/random.html)\n", "to generate\"random\" (actually pseudorandom) numbers.\n", "The functions we considered previously all generated a single\n", "random number at a time. To generate multiple random numbers,\n", "we would need to make multiple calls to the function (or\n", "nest the function in a loop that runs the appropriate number\n", "of times).\n", "\n", "The `random` module also has some extremely convenient functions\n", "dealing with sequences that allow for the generation of\n", "random orderings or lists of random numbers.\n", "\n", "As before, our first step is to import the `random` module." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import random" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Random Sample - Without Replacement\n", "\n", "To select `n` items randomly from a list without replacement,\n", "we can use the `sample(population, n)`. This function\n", "will return a list of length `n` with the samples.\n", "\n", "For instance, we could use this to simulate picking 3 marbles\n", "from a bag of marbles." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bag = ['r','r','b','g','o','o']\n", "marbles = random.sample(bag, 3)\n", "print(marbles)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The list above could have held anything (numerical types, strings,\n", "a mix, etc.) You can also call `sample` with the result of `range()` instead\n", "of with a list if you want samples from a consecutive range of integers.\n", "\n", "For example, we can randomly sample without replacement 20 integers from 1 to 100\n", "(inclusive) with:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nums = random.sample(range(1,101), 20)\n", "print(nums)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Random Choices with Replacement\n", "\n", "The previous example sampled from a list without replacement. There\n", "is also a function to sample `n` items from a list\n", "with replacement, `choices(population, k=n)`. As with `sample`,\n", "the first argument can be a list or the result of a range function.\n", "With `choices`, you must explicitly have `k=`, or it will try\n", "to interpret it as a different optional parameter.\n", "\n", "For example, we would often use\n", "choices to simulate rolling multiple dice.\n", "We can simulate rolling 8 10-sided dice with:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rolls = random.choices(range(1,11), k=8)\n", "print(rolls)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `choices` function also has the ability to accept a `weights` argument.\n", "This can be used to specify the relative weight each choice should have.\n", "\n", "For instance, suppose we were flipping an unfair coin that lands heads 80%\n", "of the time and tails 20% of the time. We could simulate 10 flips of this\n", "coin with:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "flips = random.choices(['H','T'], weights=[0.8, 0.2], k=10)\n", "print(flips)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The weights in the above could have been integers as well (so we could have\n", "used `[8,2]` to simulate the same process)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Randomly Permuting Order of Items\n", "\n", "The final useful function in the `random` module\n", "that deals with sequences is the `shuffle(seq)`\n", "function that takes `seq` and randomly shuffles\n", "the order of the elements *in-place* (meaning the\n", "original sequence is changed.)\n", "\n", "For instance, suppose we have a deck of cards (ignoring\n", "suit). We could create this deck as a list:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "deck = ['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2']*4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we wished to simulate a game, we could virtually shuffle\n", "the deck with `shuffle`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "random.shuffle(deck)\n", "print(deck)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that since `shuffle()` works in place, we didn't assign the result of `random.shuffle(deck)`\n", "to a variable." ] } ], "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.6" } }, "nbformat": 4, "nbformat_minor": 4 }