{ "metadata": { "name": "", "signature": "sha256:bb58dee3479376f436ced09c9e3ecb67e746f0ab890d644b8fbb4213130009ef" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Tuples\n", "## Manipulating tuples\n", "\n", "A tuple is an **ordered** sequence of values (any type) which makes them similar to [list](list.html), but the difference is they are immutable (i.e. you cannot modify one of the elements of a tuple on the left side of the assignment operator). The downside of this is that tuples have no methods (e.g. `append()`, `remove()`, `index()`, etc), but the upside is tuples are faster to iterate through and have additional features such as tuple assignments and string formatting that are unique to just tuples. Tuples are indexed by only integers similar to strings and lists. A tuple is defined by a sequence of comma-separated values (and can be enclosed in parentheses or not)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 'y', 'o'\n", "x = ('y', 'o')\n", "print x " ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "('y', 'o')\n" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "An empty tuple can be defined using `tuple()'" ] }, { "cell_type": "code", "collapsed": false, "input": [ "y = tuple()\n", "print y" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "()\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "which returns an empty set of parentheses or an empty tuple. \n", "\n", "If the argument of `tuple()` is a string, list or tuple, the output will be comma-separated values of the elements" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = tuple('yo')\n", "print x " ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "('y', 'o')\n" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function `len()` can be used to calculate the number elements in the tuple. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "len(x)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 4, "text": [ "2" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tuple operators \n", "Similar to strings and lists, there are many tuple operators. For example, the operators `+` and `*` also work on tuples. The operator `+` concatenate tuples and the operator `*` repeats a tuple a given number of times. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "y = tuple('lo')\n", "print x + y\n", "\n", "z = (x + y) * 3\n", "print z" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "('y', 'o', 'l', 'o')\n", "('y', 'o', 'l', 'o', 'y', 'o', 'l', 'o', 'y', 'o', 'l', 'o')\n" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Bracket operator\n", "Elements of a tuple can be extracted using the bracket operator `[]`. Tuple indices are similar to string and list indices: an integer can be used to return specific elements of a given tuple (starting with the first element as 0). If an index is negative, it returns the elements starting from the end of the tuple. The slice operator (or colon) is used to extract multiple elements of a tuple. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "z[0:3]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 6, "text": [ "('y', 'o', 'l')" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### In operator\n", "Similar to strings, lists and dictionaries, the `in` (and `not in`) operator works with tuples. The operator will check if an element is in a given tuple and return a `True` or `False`: " ] }, { "cell_type": "code", "collapsed": false, "input": [ "'s' in z" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 7, "text": [ "False" ] } ], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Relational operators\n", "The operator `is` can be used to test if two tuples are equal. The operators <, > can be used as well. Python starts by comparing the first element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements that differ. Subsequent elements are not considered (even if they are really big).\n", "\n", "## Tuple assignment\n", "A unique feature of tuples is the use of the **tuple assignment** which equates two sets of comma-separated values together across an `=` sign. For example, if you want to split the string `www.google.com` by the periods and assign each of the three sections to unique variables, you could do use the string method `split()` which will return a list with three elements. \n", "\n", "Here we assign the three substrings (separated by a `.` to the variables `start`, `middle` and `end`. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "url = 'www.google.com' \n", "start, middle, end = url.split('.')\n", "print start" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "www\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another example of tuples as return values is the built-in function `divmod` will take in two arguments (a numerator and denominator) and return two values: the quotient and a remainder as a tuple. \n", "\n", "#### Tuple assignments and string formatting \n", "The tuple assignment operator can also be very useful to format values into strings. If you have a tuple with two or more values and you want to format the values as strings and place in a specific order, you can do that. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "myfavs = ('chocolate', 'sprinkles', 'peanuts')\n", "print \"My favorite toppings are %s, %s, and %s\" % myfavs" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "My favorite toppings are chocolate, sprinkles, and peanuts\n" ] } ], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first %s is replaced by the first value in the tuple and so forth. String formatting also works with integers using the %d operator. To format numbers, use the %f operator. \n", "\n", "## Tuples: gathering and scattering arguments\n", "When defining functions with arguments, one day to define a variable-length argument is to use the `*` operator in front of the argument. This operator will **gather** a variable-length set of arguments into into a tuple. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "def toppings(*args): \n", " print args" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": {}, "source": [ "On the other hand, if you have a variable-length set of values you would like to pass to a function as multiple arguments, you can again use the `*` operator to **scatter** the arguments. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "myfavs = ('chocolate', 'sprinkles', 'peanuts')\n", "toppings(*myfavs)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "('chocolate', 'sprinkles', 'peanuts')\n" ] } ], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "which will pass the elements of the myfavs tuple to the toppings function as multiple arguments. \n", "\n", "## Zipping strings, lists and tuples\n", "The function `list()` can convert a single tuple into a list. \n", "\n", "There is a built-in function `zip` which takes in two ore more arguments and \"zips\" them into a **list** of tuples where the first element of each argument are concatenated into one tuple, the second element of each argument are concatenated into one tuple, etc. You can zip together strings, two lists or a string and a list. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "print zip('spot', 'tops')\n", "print zip([1,3,5,7], [2,4,6,8])\n", "print zip('spot', [2,4,6,8])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[('s', 't'), ('p', 'o'), ('o', 'p'), ('t', 's')]\n", "[(1, 2), (3, 4), (5, 6), (7, 8)]\n", "[('s', 2), ('p', 4), ('o', 6), ('t', 8)]\n" ] } ], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": {}, "source": [ "There is no limit on the number of arguments you can zip together.\n", "\n", "#### Loop through zipped tuples and `enumerate`\n", "You can access the elements of a tuple in a `for` loop and traverse two (or more) sequences at the same time. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "for a, b in zip('spot', [2,4,6,8]):\n", " print a, b" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "s 2\n", "p 4\n", "o 6\n", "t 8\n" ] } ], "prompt_number": 13 }, { "cell_type": "markdown", "metadata": {}, "source": [ "A `for` loop over an empty dictionary does not execute anything. \n", "\n", "The function `enumerate` is a built-in Python function that will allow the user to traverse a sequence of elements AND their indices. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "for index, value in enumerate('howdy'):\n", " print index, value" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "0 h\n", "1 o\n", "2 w\n", "3 d\n", "4 y\n" ] } ], "prompt_number": 14 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tuples and dictionaries\n", "You can create a dictionary from a list of tuples. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "d = dict(zip('spot', [2,4,6,8]))\n", "print d" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "{'p': 4, 's': 2, 't': 8, 'o': 6}\n" ] } ], "prompt_number": 15 }, { "cell_type": "markdown", "metadata": {}, "source": [ "It's common to use tuples as the keys for a dictionary (mostly because you can't use lists which are mutable). For example, you can use the first and last name as the key in a dictionary and map it to a phone number" ] }, { "cell_type": "code", "collapsed": false, "input": [ "names = {'John': 'Smith', 'Mark': 'Twain'}\n", "nums = '888-888-1000', '888-555-2000'\n", "directory = dict(zip(names.items(), nums))\n", "for first, last in directory:\n", " print first, last, directory[first, last]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Mark Twain 888-555-2000\n", "John Smith 888-888-1000\n" ] } ], "prompt_number": 16 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Combining the tuple assignment and list comprehension, you can loop through dictionaries easily. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "[\"%s=%s\" % (k, v) for k, v in names.items()]\n", "[\"%s=%s\" % (k, v) for k, v in directory.items()]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 17, "text": [ "[\"('Mark', 'Twain')=888-555-2000\", \"('John', 'Smith')=888-888-1000\"]" ] } ], "prompt_number": 17 }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the first line, we loop through all the key-value pairs in the dictionary titled \"names\" using a `for` loop, use the tuple assignment operator to name the key-value pairs, and then use string formatting to print the pairs in a specific format. \n", "\n", "## Tuple methods\n", "As stated above, because tuples are immutable, Python doesn't provide methods like `sort` and `reverse`, which modify existing lists. But Python provides the built-in functions `sorted` and `reversed`, which take any sequence as a parameter and return a new list with the same elements in a different order.\n", "\n", "## Why use tuples over lists? \n", "\n", "* Tuples are faster than lists. If iterating over a set of values, use a tuple instead of lists. \n", "* Assures your data won't be altered in the processing of your data. \n", "* Dictionary keys must be immutable and tuples are immutable. Therefore tuples can be used as keys in a dictionary (but lists cannot). \n", "* Tuple assignments allow for **string formatting** (vs concatenating strings) and **number formatting**" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 17 } ], "metadata": {} } ] }