{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Quick Reference by [Data School](http://www.dataschool.io/)\n", "\n", "**Related:** [GitHub repository](https://github.com/justmarkham/python-reference) and [blog post](http://www.dataschool.io/python-quick-reference/)\n", "\n", "## Table of contents\n", "\n", "1. Imports\n", "2. Data Types\n", "3. Math\n", "4. Comparisons and Boolean Operations\n", "5. Conditional Statements\n", "6. Lists\n", "7. Tuples\n", "8. Strings\n", "9. Dictionaries\n", "10. Sets\n", "11. Defining Functions\n", "12. Anonymous (Lambda) Functions\n", "13. For Loops and While Loops\n", "14. Comprehensions\n", "15. Map and Filter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Imports" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "5.0" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 'generic import' of math module\n", "import math\n", "math.sqrt(25)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "5.0" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# import a function\n", "from math import sqrt\n", "sqrt(25) # no longer have to reference the module" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# import multiple functions at once\n", "from math import cos, floor" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# import all functions in a module (generally discouraged)\n", "from csv import *" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# define an alias\n", "import datetime as dt" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']\n" ] } ], "source": [ "# show all functions in math module\n", "print(dir(math))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Data Types\n", "\n", "**Determine the type of an object:**" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(2)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(2.0)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type('two')" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "bool" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(True)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "NoneType" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(None)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Check if an object is of a given type:**" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(2.0, int)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(2.0, (int, float))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Convert an object to a given type:**" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2.0" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "float(2)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int(2.9)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'2.9'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(2.9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Zero, `None`, and empty containers are converted to `False`:**" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(0)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(None)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool('') # empty string" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool([]) # empty list" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool({}) # empty dictionary" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Non-empty containers and non-zeros are converted to `True`:**" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(2)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool('two')" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool([2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Math" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "14" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10 + 4" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10 - 4" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "40" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10 * 4" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "10000" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10 ** 4 # exponent" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 % 4 # modulo - computes the remainder" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Python 2: returns 2 (because both types are 'int')\n", "# Python 3: returns 2.5\n", "10 / 4" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "2.5" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10 / float(4)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# force '/' in Python 2 to perform 'true division' (unnecessary in Python 3)\n", "from __future__ import division" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2.5" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10 / 4 # true division" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10 // 4 # floor division" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Comparisons and Boolean Operations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Assignment statement:**" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": true }, "outputs": [], "source": [ "x = 5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Comparisons:**" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x > 3" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x >= 3" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x != 3" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x == 5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Boolean operations:**" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 > 3 and 6 > 3" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 > 3 or 5 < 3" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "not False" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "False or not False and True # evaluation order: not, and, or" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Conditional Statements" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "positive\n" ] } ], "source": [ "# if statement\n", "if x > 0:\n", " print('positive')" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "positive\n" ] } ], "source": [ "# if/else statement\n", "if x > 0:\n", " print('positive')\n", "else:\n", " print('zero or negative')" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "positive\n" ] } ], "source": [ "# if/elif/else statement\n", "if x > 0:\n", " print('positive')\n", "elif x == 0:\n", " print('zero')\n", "else:\n", " print('negative')" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "positive\n" ] } ], "source": [ "# single-line if statement (sometimes discouraged)\n", "if x > 0: print('positive')" ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'positive'" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# single-line if/else statement (sometimes discouraged), known as a 'ternary operator'\n", "'positive' if x > 0 else 'zero or negative'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Lists\n", "\n", "- **List properties:** ordered, iterable, mutable, can contain multiple data types" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# create an empty list (two ways)\n", "empty_list = []\n", "empty_list = list()" ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# create a list\n", "simpsons = ['homer', 'marge', 'bart']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Examine a list:**" ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'homer'" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# print element 0\n", "simpsons[0]" ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(simpsons)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Modify a list (does not return the list):**" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['homer', 'marge', 'bart', 'lisa']" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# append element to end\n", "simpsons.append('lisa')\n", "simpsons" ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# append multiple elements to end\n", "simpsons.extend(['itchy', 'scratchy'])\n", "simpsons" ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['maggie', 'homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# insert element at index 0 (shifts everything right)\n", "simpsons.insert(0, 'maggie')\n", "simpsons" ] }, { "cell_type": "code", "execution_count": 56, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['maggie', 'homer', 'marge', 'lisa', 'itchy', 'scratchy']" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# search for first instance and remove it\n", "simpsons.remove('bart')\n", "simpsons" ] }, { "cell_type": "code", "execution_count": 57, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'maggie'" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# remove element 0 and return it\n", "simpsons.pop(0)" ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['marge', 'lisa', 'itchy', 'scratchy']" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# remove element 0 (does not return it)\n", "del simpsons[0]\n", "simpsons" ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['krusty', 'lisa', 'itchy', 'scratchy']" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# replace element 0\n", "simpsons[0] = 'krusty'\n", "simpsons" ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['krusty', 'lisa', 'itchy', 'scratchy', 'ned', 'rod', 'todd']" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# concatenate lists (slower than 'extend' method)\n", "neighbors = simpsons + ['ned', 'rod', 'todd']\n", "neighbors" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Find elements in a list:**" ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# counts the number of instances\n", "simpsons.count('lisa')" ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# returns index of first instance\n", "simpsons.index('itchy')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**List slicing:**" ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "collapsed": true }, "outputs": [], "source": [ "weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']" ] }, { "cell_type": "code", "execution_count": 64, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'mon'" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# element 0\n", "weekdays[0]" ] }, { "cell_type": "code", "execution_count": 65, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['mon', 'tues', 'wed']" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# elements 0 (inclusive) to 3 (exclusive)\n", "weekdays[0:3]" ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['mon', 'tues', 'wed']" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# starting point is implied to be 0\n", "weekdays[:3]" ] }, { "cell_type": "code", "execution_count": 67, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['thurs', 'fri']" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# elements 3 (inclusive) through the end\n", "weekdays[3:]" ] }, { "cell_type": "code", "execution_count": 68, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'fri'" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# last element\n", "weekdays[-1]" ] }, { "cell_type": "code", "execution_count": 69, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['mon', 'wed', 'fri']" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# every 2nd element (step by 2)\n", "weekdays[::2]" ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['fri', 'thurs', 'wed', 'tues', 'mon']" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# backwards (step by -1)\n", "weekdays[::-1]" ] }, { "cell_type": "code", "execution_count": 71, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['fri', 'thurs', 'wed', 'tues', 'mon']" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# alternative method for returning the list backwards\n", "list(reversed(weekdays))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Sort a list in place (modifies but does not return the list):**" ] }, { "cell_type": "code", "execution_count": 72, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['itchy', 'krusty', 'lisa', 'scratchy']" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "simpsons.sort()\n", "simpsons" ] }, { "cell_type": "code", "execution_count": 73, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['scratchy', 'lisa', 'krusty', 'itchy']" ] }, "execution_count": 73, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# sort in reverse\n", "simpsons.sort(reverse=True)\n", "simpsons" ] }, { "cell_type": "code", "execution_count": 74, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['lisa', 'itchy', 'krusty', 'scratchy']" ] }, "execution_count": 74, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# sort by a key\n", "simpsons.sort(key=len)\n", "simpsons" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Return a sorted list (does not modify the original list):**" ] }, { "cell_type": "code", "execution_count": 75, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['itchy', 'krusty', 'lisa', 'scratchy']" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(simpsons)" ] }, { "cell_type": "code", "execution_count": 76, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['scratchy', 'lisa', 'krusty', 'itchy']" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(simpsons, reverse=True)" ] }, { "cell_type": "code", "execution_count": 77, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['lisa', 'itchy', 'krusty', 'scratchy']" ] }, "execution_count": 77, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(simpsons, key=len)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Insert into an already sorted list, and keep it sorted:**" ] }, { "cell_type": "code", "execution_count": 78, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[10, 20, 30, 40, 50]" ] }, "execution_count": 78, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num = [10, 20, 40, 50]\n", "from bisect import insort\n", "insort(num, 30)\n", "num" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Object references and copies:**" ] }, { "cell_type": "code", "execution_count": 79, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# create a second reference to the same list\n", "same_num = num" ] }, { "cell_type": "code", "execution_count": 80, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 20, 30, 40, 50]\n", "[0, 20, 30, 40, 50]\n" ] } ], "source": [ "# modifies both 'num' and 'same_num'\n", "same_num[0] = 0\n", "print(num)\n", "print(same_num)" ] }, { "cell_type": "code", "execution_count": 81, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# copy a list (two ways)\n", "new_num = num[:]\n", "new_num = list(num)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Examine objects:**" ] }, { "cell_type": "code", "execution_count": 82, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num is same_num # checks whether they are the same object" ] }, { "cell_type": "code", "execution_count": 83, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num is new_num" ] }, { "cell_type": "code", "execution_count": 84, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 84, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num == same_num # checks whether they have the same contents" ] }, { "cell_type": "code", "execution_count": 85, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 85, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num == new_num" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Tuples\n", "\n", "- **Tuple properties:** ordered, iterable, immutable, can contain multiple data types\n", "- Like lists, but they don't change size" ] }, { "cell_type": "code", "execution_count": 86, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# create a tuple directly\n", "digits = (0, 1, 'two')" ] }, { "cell_type": "code", "execution_count": 87, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# create a tuple from a list\n", "digits = tuple([0, 1, 'two'])" ] }, { "cell_type": "code", "execution_count": 88, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# trailing comma is required to indicate it's a tuple\n", "zero = (0,)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Examine a tuple:**" ] }, { "cell_type": "code", "execution_count": 89, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'two'" ] }, "execution_count": 89, "metadata": {}, "output_type": "execute_result" } ], "source": [ "digits[2]" ] }, { "cell_type": "code", "execution_count": 90, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 90, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(digits)" ] }, { "cell_type": "code", "execution_count": 91, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 91, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# counts the number of instances of that value\n", "digits.count(0)" ] }, { "cell_type": "code", "execution_count": 92, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 92, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# returns the index of the first instance of that value\n", "digits.index(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Modify a tuple:**" ] }, { "cell_type": "code", "execution_count": 93, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# elements of a tuple cannot be modified (this would throw an error)\n", "# digits[2] = 2" ] }, { "cell_type": "code", "execution_count": 94, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(0, 1, 'two', 3, 4)" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# concatenate tuples\n", "digits = digits + (3, 4)\n", "digits" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Other tuple operations:**" ] }, { "cell_type": "code", "execution_count": 95, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(3, 4, 3, 4)" ] }, "execution_count": 95, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# create a single tuple with elements repeated (also works with lists)\n", "(3, 4) * 2" ] }, { "cell_type": "code", "execution_count": 96, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[(10, 40), (20, 30), (20, 60)]" ] }, "execution_count": 96, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# sort a list of tuples\n", "tens = [(20, 60), (10, 40), (20, 30)]\n", "sorted(tens) # sorts by first element in tuple, then second element" ] }, { "cell_type": "code", "execution_count": 97, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "male\n", "10\n", "simpson\n" ] } ], "source": [ "# tuple unpacking\n", "bart = ('male', 10, 'simpson') # create a tuple\n", "(sex, age, surname) = bart # assign three values at once\n", "print(sex)\n", "print(age)\n", "print(surname)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8. Strings\n", "\n", "- **String properties:** iterable, immutable" ] }, { "cell_type": "code", "execution_count": 98, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'42'" ] }, "execution_count": 98, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# convert another data type into a string\n", "s = str(42)\n", "s" ] }, { "cell_type": "code", "execution_count": 99, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# create a string directly\n", "s = 'I like you'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Examine a string:**" ] }, { "cell_type": "code", "execution_count": 100, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'I'" ] }, "execution_count": 100, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s[0]" ] }, { "cell_type": "code", "execution_count": 101, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 101, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**String slicing is like list slicing:**" ] }, { "cell_type": "code", "execution_count": 102, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'I like'" ] }, "execution_count": 102, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s[:6]" ] }, { "cell_type": "code", "execution_count": 103, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'you'" ] }, "execution_count": 103, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s[7:]" ] }, { "cell_type": "code", "execution_count": 104, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'u'" ] }, "execution_count": 104, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s[-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Basic string methods (does not modify the original string):**" ] }, { "cell_type": "code", "execution_count": 105, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'i like you'" ] }, "execution_count": 105, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.lower()" ] }, { "cell_type": "code", "execution_count": 106, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'I LIKE YOU'" ] }, "execution_count": 106, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.upper()" ] }, { "cell_type": "code", "execution_count": 107, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 107, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.startswith('I')" ] }, { "cell_type": "code", "execution_count": 108, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 108, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.endswith('you')" ] }, { "cell_type": "code", "execution_count": 109, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 109, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# checks whether every character in the string is a digit\n", "s.isdigit()" ] }, { "cell_type": "code", "execution_count": 110, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 110, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# returns index of first occurrence, but doesn't support regex\n", "s.find('like')" ] }, { "cell_type": "code", "execution_count": 111, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "-1" ] }, "execution_count": 111, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# returns -1 since not found\n", "s.find('hate')" ] }, { "cell_type": "code", "execution_count": 112, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'I love you'" ] }, "execution_count": 112, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# replaces all instances of 'like' with 'love'\n", "s.replace('like', 'love')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Split a string:**" ] }, { "cell_type": "code", "execution_count": 113, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['I', 'like', 'you']" ] }, "execution_count": 113, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# split a string into a list of substrings separated by a delimiter\n", "s.split(' ')" ] }, { "cell_type": "code", "execution_count": 114, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['I', 'like', 'you']" ] }, "execution_count": 114, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# equivalent (since space is the default delimiter)\n", "s.split()" ] }, { "cell_type": "code", "execution_count": 115, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['a', ' an', ' the']" ] }, "execution_count": 115, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s2 = 'a, an, the'\n", "s2.split(',')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Join or concatenate strings:**" ] }, { "cell_type": "code", "execution_count": 116, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'larry curly moe'" ] }, "execution_count": 116, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# join a list of strings into one string using a delimiter\n", "stooges = ['larry', 'curly', 'moe']\n", "' '.join(stooges)" ] }, { "cell_type": "code", "execution_count": 117, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'The meaning of life is 42'" ] }, "execution_count": 117, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# concatenate strings\n", "s3 = 'The meaning of life is'\n", "s4 = '42'\n", "s3 + ' ' + s4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Remove whitespace from the start and end of a string:**" ] }, { "cell_type": "code", "execution_count": 118, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'ham and cheese'" ] }, "execution_count": 118, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s5 = ' ham and cheese '\n", "s5.strip()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**String substitutions:**" ] }, { "cell_type": "code", "execution_count": 119, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'raining cats and dogs'" ] }, "execution_count": 119, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# old way\n", "'raining %s and %s' % ('cats', 'dogs')" ] }, { "cell_type": "code", "execution_count": 120, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'raining cats and dogs'" ] }, "execution_count": 120, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# new way\n", "'raining {} and {}'.format('cats', 'dogs')" ] }, { "cell_type": "code", "execution_count": 121, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'raining cats and dogs'" ] }, "execution_count": 121, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# new way (using named arguments)\n", "'raining {arg1} and {arg2}'.format(arg1='cats', arg2='dogs')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**String formatting ([more examples](https://mkaz.tech/python-string-format.html)):**" ] }, { "cell_type": "code", "execution_count": 122, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'pi is 3.14'" ] }, "execution_count": 122, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# use 2 decimal places\n", "'pi is {:.2f}'.format(3.14159)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Normal strings versus raw strings:**" ] }, { "cell_type": "code", "execution_count": 123, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "first line\n", "second line\n" ] } ], "source": [ "# normal strings allow for escaped characters\n", "print('first line\\nsecond line')" ] }, { "cell_type": "code", "execution_count": 124, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "first line\\nfirst line\n" ] } ], "source": [ "# raw strings treat backslashes as literal characters\n", "print(r'first line\\nfirst line')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9. Dictionaries\n", "\n", "- **Dictionary properties:** unordered, iterable, mutable, can contain multiple data types\n", "- Made of key-value pairs\n", "- Keys must be unique, and can be strings, numbers, or tuples\n", "- Values can be any type" ] }, { "cell_type": "code", "execution_count": 125, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# create an empty dictionary (two ways)\n", "empty_dict = {}\n", "empty_dict = dict()" ] }, { "cell_type": "code", "execution_count": 126, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'dad': 'homer', 'mom': 'marge', 'size': 6}" ] }, "execution_count": 126, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# create a dictionary (two ways)\n", "family = {'dad':'homer', 'mom':'marge', 'size':6}\n", "family = dict(dad='homer', mom='marge', size=6)\n", "family" ] }, { "cell_type": "code", "execution_count": 127, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'dad': 'homer', 'mom': 'marge', 'size': 6}" ] }, "execution_count": 127, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# convert a list of tuples into a dictionary\n", "list_of_tuples = [('dad', 'homer'), ('mom', 'marge'), ('size', 6)]\n", "family = dict(list_of_tuples)\n", "family" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Examine a dictionary:**" ] }, { "cell_type": "code", "execution_count": 128, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'homer'" ] }, "execution_count": 128, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# pass a key to return its value\n", "family['dad']" ] }, { "cell_type": "code", "execution_count": 129, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 129, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# return the number of key-value pairs\n", "len(family)" ] }, { "cell_type": "code", "execution_count": 130, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 130, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# check if key exists in dictionary\n", "'mom' in family" ] }, { "cell_type": "code", "execution_count": 131, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 131, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# dictionary values are not checked\n", "'marge' in family" ] }, { "cell_type": "code", "execution_count": 132, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['dad', 'mom', 'size']" ] }, "execution_count": 132, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# returns a list of keys (Python 2) or an iterable view (Python 3)\n", "family.keys()" ] }, { "cell_type": "code", "execution_count": 133, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['homer', 'marge', 6]" ] }, "execution_count": 133, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# returns a list of values (Python 2) or an iterable view (Python 3)\n", "family.values()" ] }, { "cell_type": "code", "execution_count": 134, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[('dad', 'homer'), ('mom', 'marge'), ('size', 6)]" ] }, "execution_count": 134, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# returns a list of key-value pairs (Python 2) or an iterable view (Python 3)\n", "family.items()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Modify a dictionary (does not return the dictionary):**" ] }, { "cell_type": "code", "execution_count": 135, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'cat': 'snowball', 'dad': 'homer', 'mom': 'marge', 'size': 6}" ] }, "execution_count": 135, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# add a new entry\n", "family['cat'] = 'snowball'\n", "family" ] }, { "cell_type": "code", "execution_count": 136, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'cat': 'snowball ii', 'dad': 'homer', 'mom': 'marge', 'size': 6}" ] }, "execution_count": 136, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# edit an existing entry\n", "family['cat'] = 'snowball ii'\n", "family" ] }, { "cell_type": "code", "execution_count": 137, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'dad': 'homer', 'mom': 'marge', 'size': 6}" ] }, "execution_count": 137, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# delete an entry\n", "del family['cat']\n", "family" ] }, { "cell_type": "code", "execution_count": 138, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'dad': 'homer', 'kids': ['bart', 'lisa'], 'mom': 'marge', 'size': 6}" ] }, "execution_count": 138, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# dictionary value can be a list\n", "family['kids'] = ['bart', 'lisa']\n", "family" ] }, { "cell_type": "code", "execution_count": 139, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'homer'" ] }, "execution_count": 139, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# remove an entry and return the value\n", "family.pop('dad')" ] }, { "cell_type": "code", "execution_count": 140, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'baby': 'maggie',\n", " 'grandpa': 'abe',\n", " 'kids': ['bart', 'lisa'],\n", " 'mom': 'marge',\n", " 'size': 6}" ] }, "execution_count": 140, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# add multiple entries\n", "family.update({'baby':'maggie', 'grandpa':'abe'})\n", "family" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Access values more safely with `get`:**" ] }, { "cell_type": "code", "execution_count": 141, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'marge'" ] }, "execution_count": 141, "metadata": {}, "output_type": "execute_result" } ], "source": [ "family['mom']" ] }, { "cell_type": "code", "execution_count": 142, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'marge'" ] }, "execution_count": 142, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# equivalent to a dictionary lookup\n", "family.get('mom')" ] }, { "cell_type": "code", "execution_count": 143, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# this would throw an error since the key does not exist\n", "# family['grandma']" ] }, { "cell_type": "code", "execution_count": 144, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# return None if not found\n", "family.get('grandma')" ] }, { "cell_type": "code", "execution_count": 145, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'not found'" ] }, "execution_count": 145, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# provide a default return value if not found\n", "family.get('grandma', 'not found')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Access a list element within a dictionary:**" ] }, { "cell_type": "code", "execution_count": 146, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'bart'" ] }, "execution_count": 146, "metadata": {}, "output_type": "execute_result" } ], "source": [ "family['kids'][0]" ] }, { "cell_type": "code", "execution_count": 147, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'baby': 'maggie',\n", " 'grandpa': 'abe',\n", " 'kids': ['bart'],\n", " 'mom': 'marge',\n", " 'size': 6}" ] }, "execution_count": 147, "metadata": {}, "output_type": "execute_result" } ], "source": [ "family['kids'].remove('lisa')\n", "family" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**String substitution using a dictionary:**" ] }, { "cell_type": "code", "execution_count": 148, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'youngest child is maggie'" ] }, "execution_count": 148, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'youngest child is %(baby)s' % family" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 10. Sets\n", "\n", "- **Set properties:** unordered, iterable, mutable, can contain multiple data types\n", "- Made of unique elements (strings, numbers, or tuples)\n", "- Like dictionaries, but with keys only (no values)" ] }, { "cell_type": "code", "execution_count": 149, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# create an empty set\n", "empty_set = set()" ] }, { "cell_type": "code", "execution_count": 150, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# create a set directly\n", "languages = {'python', 'r', 'java'}" ] }, { "cell_type": "code", "execution_count": 151, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# create a set from a list\n", "snakes = set(['cobra', 'viper', 'python'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Examine a set:**" ] }, { "cell_type": "code", "execution_count": 152, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 152, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(languages)" ] }, { "cell_type": "code", "execution_count": 153, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 153, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'python' in languages" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Set operations:**" ] }, { "cell_type": "code", "execution_count": 154, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'python'}" ] }, "execution_count": 154, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# intersection\n", "languages & snakes" ] }, { "cell_type": "code", "execution_count": 155, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'cobra', 'java', 'python', 'r', 'viper'}" ] }, "execution_count": 155, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# union\n", "languages | snakes" ] }, { "cell_type": "code", "execution_count": 156, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'java', 'r'}" ] }, "execution_count": 156, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# set difference\n", "languages - snakes" ] }, { "cell_type": "code", "execution_count": 157, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'cobra', 'viper'}" ] }, "execution_count": 157, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# set difference\n", "snakes - languages" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Modify a set (does not return the set):**" ] }, { "cell_type": "code", "execution_count": 158, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'java', 'python', 'r', 'sql'}" ] }, "execution_count": 158, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# add a new element\n", "languages.add('sql')\n", "languages" ] }, { "cell_type": "code", "execution_count": 159, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'java', 'python', 'r', 'sql'}" ] }, "execution_count": 159, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# try to add an existing element (ignored, no error)\n", "languages.add('r')\n", "languages" ] }, { "cell_type": "code", "execution_count": 160, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'python', 'r', 'sql'}" ] }, "execution_count": 160, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# remove an element\n", "languages.remove('java')\n", "languages" ] }, { "cell_type": "code", "execution_count": 161, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# try to remove a non-existing element (this would throw an error)\n", "# languages.remove('c')" ] }, { "cell_type": "code", "execution_count": 162, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'python', 'r', 'sql'}" ] }, "execution_count": 162, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# remove an element if present, but ignored otherwise\n", "languages.discard('c')\n", "languages" ] }, { "cell_type": "code", "execution_count": 163, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'python'" ] }, "execution_count": 163, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# remove and return an arbitrary element\n", "languages.pop()" ] }, { "cell_type": "code", "execution_count": 164, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "set()" ] }, "execution_count": 164, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# remove all elements\n", "languages.clear()\n", "languages" ] }, { "cell_type": "code", "execution_count": 165, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'go', 'spark'}" ] }, "execution_count": 165, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# add multiple elements (can also pass a set)\n", "languages.update(['go', 'spark'])\n", "languages" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Get a sorted list of unique elements from a list:**" ] }, { "cell_type": "code", "execution_count": 166, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2, 9]" ] }, "execution_count": 166, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(set([9, 0, 2, 1, 0]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 11. Defining Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Define a function with no arguments and no return values:**" ] }, { "cell_type": "code", "execution_count": 167, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def print_text():\n", " print('this is text')" ] }, { "cell_type": "code", "execution_count": 168, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "this is text\n" ] } ], "source": [ "# call the function\n", "print_text()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Define a function with one argument and no return values:**" ] }, { "cell_type": "code", "execution_count": 169, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def print_this(x):\n", " print(x)" ] }, { "cell_type": "code", "execution_count": 170, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "# call the function\n", "print_this(3)" ] }, { "cell_type": "code", "execution_count": 171, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "# prints 3, but doesn't assign 3 to n because the function has no return statement\n", "n = print_this(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Define a function with one argument and one return value:**" ] }, { "cell_type": "code", "execution_count": 172, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def square_this(x):\n", " return x**2" ] }, { "cell_type": "code", "execution_count": 173, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# include an optional docstring to describe the effect of a function\n", "def square_this(x):\n", " \"\"\"Return the square of a number.\"\"\"\n", " return x**2" ] }, { "cell_type": "code", "execution_count": 174, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 174, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# call the function\n", "square_this(3)" ] }, { "cell_type": "code", "execution_count": 175, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# assigns 9 to var, but does not print 9\n", "var = square_this(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Define a function with two 'positional arguments' (no default values) and one 'keyword argument' (has a default value):**\n" ] }, { "cell_type": "code", "execution_count": 176, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def calc(a, b, op='add'):\n", " if op == 'add':\n", " return a + b\n", " elif op == 'sub':\n", " return a - b\n", " else:\n", " print('valid operations are add and sub')" ] }, { "cell_type": "code", "execution_count": 177, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "14" ] }, "execution_count": 177, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# call the function\n", "calc(10, 4, op='add')" ] }, { "cell_type": "code", "execution_count": 178, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "14" ] }, "execution_count": 178, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# unnamed arguments are inferred by position\n", "calc(10, 4, 'add')" ] }, { "cell_type": "code", "execution_count": 179, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "14" ] }, "execution_count": 179, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# default for 'op' is 'add'\n", "calc(10, 4)" ] }, { "cell_type": "code", "execution_count": 180, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 180, "metadata": {}, "output_type": "execute_result" } ], "source": [ "calc(10, 4, 'sub')" ] }, { "cell_type": "code", "execution_count": 181, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "valid operations are add and sub\n" ] } ], "source": [ "calc(10, 4, 'div')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Use `pass` as a placeholder if you haven't written the function body:**" ] }, { "cell_type": "code", "execution_count": 182, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def stub():\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Return two values from a single function:**" ] }, { "cell_type": "code", "execution_count": 183, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def min_max(nums):\n", " return min(nums), max(nums)" ] }, { "cell_type": "code", "execution_count": 184, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(1, 3)" ] }, "execution_count": 184, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# return values can be assigned to a single variable as a tuple\n", "nums = [1, 2, 3]\n", "min_max_num = min_max(nums)\n", "min_max_num" ] }, { "cell_type": "code", "execution_count": 185, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "3\n" ] } ], "source": [ "# return values can be assigned into multiple variables using tuple unpacking\n", "min_num, max_num = min_max(nums)\n", "print(min_num)\n", "print(max_num)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 12. Anonymous (Lambda) Functions\n", "\n", "- Primarily used to temporarily define a function for use by another function" ] }, { "cell_type": "code", "execution_count": 186, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# define a function the \"usual\" way\n", "def squared(x):\n", " return x**2" ] }, { "cell_type": "code", "execution_count": 187, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# define an identical function using lambda\n", "squared = lambda x: x**2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Sort a list of strings by the last letter:**" ] }, { "cell_type": "code", "execution_count": 188, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['marge', 'homer', 'bart']" ] }, "execution_count": 188, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# without using lambda\n", "simpsons = ['homer', 'marge', 'bart']\n", "def last_letter(word):\n", " return word[-1]\n", "sorted(simpsons, key=last_letter)" ] }, { "cell_type": "code", "execution_count": 189, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['marge', 'homer', 'bart']" ] }, "execution_count": 189, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# using lambda\n", "sorted(simpsons, key=lambda word: word[-1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 13. For Loops and While Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**`range` returns a list of integers (Python 2) or a sequence (Python 3):**" ] }, { "cell_type": "code", "execution_count": 190, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2]" ] }, "execution_count": 190, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# includes the start value but excludes the stop value\n", "range(0, 3)" ] }, { "cell_type": "code", "execution_count": 191, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2]" ] }, "execution_count": 191, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# default start value is 0\n", "range(3)" ] }, { "cell_type": "code", "execution_count": 192, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0, 2, 4]" ] }, "execution_count": 192, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# third argument is the step value\n", "range(0, 5, 2)" ] }, { "cell_type": "code", "execution_count": 193, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "xrange(100, 100000, 5)" ] }, "execution_count": 193, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Python 2 only: use xrange to create a sequence rather than a list (saves memory)\n", "xrange(100, 100000, 5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**`for` loops:**" ] }, { "cell_type": "code", "execution_count": 194, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "APPLE\n", "BANANA\n", "CHERRY\n" ] } ], "source": [ "# not the recommended style\n", "fruits = ['apple', 'banana', 'cherry']\n", "for i in range(len(fruits)):\n", " print(fruits[i].upper())" ] }, { "cell_type": "code", "execution_count": 195, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "APPLE\n", "BANANA\n", "CHERRY\n" ] } ], "source": [ "# recommended style\n", "for fruit in fruits:\n", " print(fruit.upper())" ] }, { "cell_type": "code", "execution_count": 196, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('dad', 'homer')\n", "('mom', 'marge')\n", "('size', 6)\n" ] } ], "source": [ "# iterate through two things at once (using tuple unpacking)\n", "family = {'dad':'homer', 'mom':'marge', 'size':6}\n", "for key, value in family.items():\n", " print(key, value)" ] }, { "cell_type": "code", "execution_count": 197, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(0, 'apple')\n", "(1, 'banana')\n", "(2, 'cherry')\n" ] } ], "source": [ "# use enumerate if you need to access the index value within the loop\n", "for index, fruit in enumerate(fruits):\n", " print(index, fruit)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**`for`/`else` loop:**" ] }, { "cell_type": "code", "execution_count": 198, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found the banana!\n" ] } ], "source": [ "for fruit in fruits:\n", " if fruit == 'banana':\n", " print('Found the banana!')\n", " break # exit the loop and skip the 'else' block\n", "else:\n", " # this block executes ONLY if the for loop completes without hitting 'break'\n", " print(\"Can't find the banana\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**`while` loop:**" ] }, { "cell_type": "code", "execution_count": 199, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This will print 5 times\n", "This will print 5 times\n", "This will print 5 times\n", "This will print 5 times\n", "This will print 5 times\n" ] } ], "source": [ "count = 0\n", "while count < 5:\n", " print('This will print 5 times')\n", " count += 1 # equivalent to 'count = count + 1'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 14. Comprehensions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**List comprehension:**" ] }, { "cell_type": "code", "execution_count": 200, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 8, 27, 64, 125]" ] }, "execution_count": 200, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# for loop to create a list of cubes\n", "nums = [1, 2, 3, 4, 5]\n", "cubes = []\n", "for num in nums:\n", " cubes.append(num**3)\n", "cubes" ] }, { "cell_type": "code", "execution_count": 201, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 8, 27, 64, 125]" ] }, "execution_count": 201, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# equivalent list comprehension\n", "cubes = [num**3 for num in nums]\n", "cubes" ] }, { "cell_type": "code", "execution_count": 202, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[8, 64]" ] }, "execution_count": 202, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# for loop to create a list of cubes of even numbers\n", "cubes_of_even = []\n", "for num in nums:\n", " if num % 2 == 0:\n", " cubes_of_even.append(num**3)\n", "cubes_of_even" ] }, { "cell_type": "code", "execution_count": 203, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[8, 64]" ] }, "execution_count": 203, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# equivalent list comprehension\n", "# syntax: [expression for variable in iterable if condition]\n", "cubes_of_even = [num**3 for num in nums if num % 2 == 0]\n", "cubes_of_even" ] }, { "cell_type": "code", "execution_count": 204, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 8, 9, 64, 25]" ] }, "execution_count": 204, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# for loop to cube even numbers and square odd numbers\n", "cubes_and_squares = []\n", "for num in nums:\n", " if num % 2 == 0:\n", " cubes_and_squares.append(num**3)\n", " else:\n", " cubes_and_squares.append(num**2)\n", "cubes_and_squares" ] }, { "cell_type": "code", "execution_count": 205, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 8, 9, 64, 25]" ] }, "execution_count": 205, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# equivalent list comprehension (using a ternary expression)\n", "# syntax: [true_condition if condition else false_condition for variable in iterable]\n", "cubes_and_squares = [num**3 if num % 2 == 0 else num**2 for num in nums]\n", "cubes_and_squares" ] }, { "cell_type": "code", "execution_count": 206, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4]" ] }, "execution_count": 206, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# for loop to flatten a 2d-matrix\n", "matrix = [[1, 2], [3, 4]]\n", "items = []\n", "for row in matrix:\n", " for item in row:\n", " items.append(item)\n", "items" ] }, { "cell_type": "code", "execution_count": 207, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4]" ] }, "execution_count": 207, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# equivalent list comprehension\n", "items = [item for row in matrix\n", " for item in row]\n", "items" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Set comprehension:**" ] }, { "cell_type": "code", "execution_count": 208, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{5, 6}" ] }, "execution_count": 208, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fruits = ['apple', 'banana', 'cherry']\n", "unique_lengths = {len(fruit) for fruit in fruits}\n", "unique_lengths" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Dictionary comprehension:**" ] }, { "cell_type": "code", "execution_count": 209, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'apple': 5, 'banana': 6, 'cherry': 6}" ] }, "execution_count": 209, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fruit_lengths = {fruit:len(fruit) for fruit in fruits}\n", "fruit_lengths" ] }, { "cell_type": "code", "execution_count": 210, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'apple': 0, 'banana': 1, 'cherry': 2}" ] }, "execution_count": 210, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fruit_indices = {fruit:index for index, fruit in enumerate(fruits)}\n", "fruit_indices" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 15. Map and Filter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**`map` applies a function to every element of a sequence and returns a list (Python 2) or iterator (Python 3):**" ] }, { "cell_type": "code", "execution_count": 211, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[5, 5, 4]" ] }, "execution_count": 211, "metadata": {}, "output_type": "execute_result" } ], "source": [ "simpsons = ['homer', 'marge', 'bart']\n", "map(len, simpsons)" ] }, { "cell_type": "code", "execution_count": 212, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[5, 5, 4]" ] }, "execution_count": 212, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# equivalent list comprehension\n", "[len(word) for word in simpsons]" ] }, { "cell_type": "code", "execution_count": 213, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['r', 'e', 't']" ] }, "execution_count": 213, "metadata": {}, "output_type": "execute_result" } ], "source": [ "map(lambda word: word[-1], simpsons)" ] }, { "cell_type": "code", "execution_count": 214, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['r', 'e', 't']" ] }, "execution_count": 214, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# equivalent list comprehension\n", "[word[-1] for word in simpsons]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**`filter` returns a list (Python 2) or iterator (Python 3) containing the elements from a sequence for which a condition is `True`:**" ] }, { "cell_type": "code", "execution_count": 215, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0, 2, 4]" ] }, "execution_count": 215, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nums = range(5)\n", "filter(lambda x: x % 2 == 0, nums)" ] }, { "cell_type": "code", "execution_count": 216, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0, 2, 4]" ] }, "execution_count": 216, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# equivalent list comprehension\n", "[num for num in nums if num % 2 == 0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top]" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.11" } }, "nbformat": 4, "nbformat_minor": 0 }