{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Tuples\n", "\n", "We've seen a couple examples of sequences so far, namely, lists and strings.\n", "Tuples are another type of sequence that are similar to both lists and strings.\n", "Like strings (but unlike lists), tuples are *immutable* meaning it is impossible to change what\n", "is stored in them. However, like lists (and unlike strings), tuples can contain things\n", "other than characters. For example, tuples can contain numeric values, strings,\n", "booleans, lists, other tuples, etc.\n", "\n", "## Tuple Creation\n", "To create a tuple, we enclose the items in the tuple in parentheses and separate them\n", "by commas (essentially like a list but enclosed with `(` and `)` instead of `[` and `]`).\n", "\n", "For example," ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tnum = (4,5,6)\n", "print(type(tnum))\n", "tstr = ('x', 'y', 'z')\n", "print(type(tstr))\n", "tmix = ('a', 1, [9,10], (-9, 10))\n", "print(type(tmix))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that since parentheses are also used to group operations to specify\n", "precedence, if we wish to have a tuple with a single element, we cannot merely\n", "enclose the single element in parentheses, i.e., `(1)`. Instead, we must add\n", "in a trailing comma after the only element to indicate that we actually want a tuple." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nocomma = (1)\n", "tsingle = (1,)\n", "print(type(nocomma))\n", "print(type(tsingle))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You may wonder why in the world you would want to create a tuple with\n", "only one element. It's fairly common for functions in libraries to\n", "take in a tuple as an argument, as a general way of accepting an argument\n", "that could be a single value or could involve more than one. In these\n", "cases if you only want that argument to be a specific value, then you would often create a tuple with just the one value." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Tuples from other Sequences\n", "The final way we can create a tuple is from an existing sequence. We can use existing\n", "lists or strings to create tuples, much like we could create a list of the characters\n", "in a string. To do this, we call `tuple(seq)`, where `seq` is the existing sequence.\n", "\n", "For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lst = [1,2,3]\n", "tuplst = tuple(lst)\n", "print(type(tuplst))\n", "print(tuplst)\n", "\n", "msg = \"hello\"\n", "tupstr = tuple(msg)\n", "print(type(tupstr))\n", "print(tupstr)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tuple Operations\n", "Although tuples behave somewhat similarly to both lists and\n", "strings, unlike both they do not have the wide variety of methods.\n", "However, they do share the common set of \n", "sequence operations with both lists and strings (these\n", "should hopefully look familiar at this point).\n", "In particular, tuples have the following possible operations\n", "\n", "### Accessing\n", "* indexing with standard bracket notation `t[index]`\n", "* slicing with `t[start:stop]` or `t[start:stop:step]` (where any can be empty)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tup = ('p', 3, 1, 5, 'i', 9)\n", "print(tup[1])\n", "print(tup[1:])\n", "print(tup[:4:2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Operators\n", "* concatenation with `+` operator\n", "* repetition with `*` operator" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t1 = ('4', '0', '6')\n", "t2 = ('4', '7', '3')\n", "print(t1)\n", "print(t1+t2)\n", "print(t1*2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Applicable Functions and Methods\n", "* length with `len(t)`\n", "* minimum with `min(t)`\n", "* maximum with `max(t)`\n", "* index of first occurrence of item with `t.index(item)`. As with lists, raises `ValueError` if \n", " `item` is not in `t`.\n", "* count of number of occurrences of item with `t.count(item)`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t1 = ('z', 'z', 'a', 'p', 'a', 'q', 'z')\n", "print('len = ', len(t1))\n", "print('min = ', min(t1))\n", "print('max = ', max(t1))\n", "print(\"index of 'a' =\", t1.index('a'))\n", "print(\"count of 'z' =\", t1.count('z'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Containment and Iteration\n", "* check for value with `val in t`. Recall this will evaluate to `True` or `False`, and\n", " is typically used as part of a conditional to effect the behavior.\n", "* loop through values with `for val in t`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tup = (1, 5, -2, 8)\n", "print(1 in tup)\n", "print(2 in tup)\n", "\n", "for val in tup:\n", " print(val**2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Comparison\n", "* comparison with `<`, `<=`, `>`, `>=`\n", "* comparison is lexicographical\n", " * less than -> \"comes before\" -- checks which has 1st element coming first.\n", " * if first element is equal, moves on to next element, etc." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t1 = ('4', '0', '6')\n", "t2 = ('4', '7', '3')\n", "print(t1 < t2)\n", "t1 = ('4', '0', '6')\n", "t2 = ('4', '-8', '3')\n", "print(t1 < t2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Immutability\n", "\n", "As mentioned previously, tuples are immutable. Thus, although we\n", "can use indexing to access specific elements in the tuple, we\n", "cannot change the element in that spot in the tuple. In fact, like\n", "we saw with strings, attempting to do so will cause your program\n", "to have an error.\n", "\n", "For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t = ('a','b','c')\n", "t[0] = 'z'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Although tuples themselves are immutable, they can still contain references to mutable objects.\n", "Since tuples are immutable, the references contained in the tuple cannot change. However,\n", "the underlying objects referenced can be modified. For instance, consider:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t = (3.5, [1,2])\n", "# t[1] = 3 # can't do this\n", "t[1][1] = 3\n", "print(t)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Packing & Unpacking\n", "Often times it is helpful to combine existing values (\"pack\") them into a tuple.\n", "In these cases, we can omit the parentheses entirely. This is known as *packing*.\n", "We accomplish this by just assigning comma-separated values to a variable." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t = 2,4,5\n", "print(type(t))\n", "print(t)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Likewise, and potentially even more common is the desire to separate\n", "out the specific elements in a tuple into separate variables. This is known\n", "as *unpacking*. This is accomplished by listing the desired (\"unpacked\")\n", "variable names on the left side of the assignment statement, and the variable\n", "name for the tuple on the right." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tup = ('erin', 'bob', 'susie')\n", "first, second, third = tup\n", "print(first)\n", "print(type(first))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These notations can be a little different at first. The easiest way to\n", "keep them straight is to remember that the right hand side is always\n", "computed/executed first, then the values are merely assigned to the left\n", "hand side." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## When and Why to Use Tuples?\n", "A natural question to ask is if tuples are so similar to\n", "both lists and strings, what is their purpose. While it's\n", "possible to accomplish many of the same tasks with lists, there\n", "are use cases for when tuples are necessary or more appropriate.\n", "\n", "* When a sequence of items should not be altered.\n", " * Using tuples can force non-alteration\n", " * While not necessary, selective use can prevent\n", " unwittingly modifying a sequence in a function\n", "* Efficiency: because they are immutable, tuples are more\n", " efficient than lists\n", "* With functions returning more than one value\n", " * Standard form `return val1, val2, val3, ...`\n", " * This actually packs the values listed into a tuple\n", " and returns the tuple\n", " * Not strictly required (could make a different type of sequence\n", " and return it, but one should only do that if there is a\n", " necessary reason)\n", " * Assigning result returned by function to multiple variables\n", " * Most common use of \"unpacking\"\n", " * Example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_stats(lst):\n", " small = min(lst)\n", " big = max(lst)\n", " return small, big # packs into tuple when returning\n", "\n", "lst = [39, 41, 18, 49, 25]\n", "mn, mx = get_stats(lst) # unpacks into 2 variables\n", "print(mn, mx)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Sometimes just convenient to accomplish task\n", " * Example: swapping values in two variables\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "p = 4\n", "q = 10\n", "p,q = q,p\n", "print(p,q)" ] } ], "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 }