├── .gitignore ├── README.md ├── reference.ipynb └── reference.py /.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoints/ 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Python Quick Reference 2 | 3 | ### View as a [Python script](reference.py) or a [Jupyter notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb) 4 | 5 | This is the reference guide to Python that I **wish** had existed when I was learning the language. 6 | 7 | Here's what I want in a reference guide: 8 | 9 | - **High-quality examples** that show the simplest possible usage of a given feature 10 | - **Explanatory comments**, and descriptive variable names that eliminate the need for some comments 11 | - Presented as a **single script (or notebook)**, so that I can keep it open and search it when needed 12 | - **Code that can be run** from top to bottom, with the relevant objects defined nearby 13 | 14 | This is **not** written as a full-fledged Python tutorial, though I ordered the topics such that you can read it like a tutorial (i.e., each topic depends only on material preceding it). 15 | 16 | The guide was written using Python 2 but is **fully compatible** with Python 3. Relevant differences between Python 2 and 3 are noted throughout the guide. 17 | 18 | ### Table of Contents 19 | 20 | Click to jump to the relevant section of the script or the notebook: 21 | 22 | 1. Imports ([script](reference.py#L28), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#1.-Imports)) 23 | 2. Data Types ([script](reference.py#L52), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#2.-Data-Types)) 24 | 3. Math ([script](reference.py#L84), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#3.-Math)) 25 | 4. Comparisons and Boolean Operations ([script](reference.py#L102), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#4.-Comparisons-and-Boolean-Operations)) 26 | 5. Conditional Statements ([script](reference.py#L121), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#5.-Conditional-Statements)) 27 | 6. Lists ([script](reference.py#L150), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#6.-Lists)) 28 | 7. Tuples ([script](reference.py#L224), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#7.-Tuples)) 29 | 8. Strings ([script](reference.py#L259), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#8.-Strings)) 30 | 9. Dictionaries ([script](reference.py#L319), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#9.-Dictionaries)) 31 | 10. Sets ([script](reference.py#L372), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#10.-Sets)) 32 | 11. Defining Functions ([script](reference.py#L409), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#11.-Defining-Functions)) 33 | 12. Anonymous (Lambda) Functions ([script](reference.py#L474), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#12.-Anonymous-%28Lambda%29-Functions)) 34 | 13. For Loops and While Loops ([script](reference.py#L495), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#13.-For-Loops-and-While-Loops)) 35 | 14. Comprehensions ([script](reference.py#L540), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#14.-Comprehensions)) 36 | 15. Map and Filter ([script](reference.py#L594), [notebook](http://nbviewer.jupyter.org/github/justmarkham/python-reference/blob/master/reference.ipynb#15.-Map-and-Filter)) 37 | 38 | ### Other Python Resources 39 | 40 | If you like the general format of this guide, but need **more explanation of each topic**, I highly recommend reading the Appendix of [Python for Data Analysis](http://shop.oreilly.com/product/0636920023784.do). It presents the essentials of the Python language in a clear and focused manner. 41 | 42 | If you are looking for a resource that will help you to **learn Python from scratch**, this is [my list of recommended resources](https://github.com/justmarkham/DAT8#python-resources). 43 | 44 | ### Suggestions or Corrections 45 | 46 | If there's a **topic or example** you'd like me to add to this guide, or you notice a **mistake**, please [create a GitHub issue](../../issues) or [leave a blog comment](http://www.dataschool.io/python-quick-reference/). 47 | 48 | Thank you! 49 | -------------------------------------------------------------------------------- /reference.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Python Quick Reference by [Data School](http://www.dataschool.io/)\n", 8 | "\n", 9 | "**Related:** [GitHub repository](https://github.com/justmarkham/python-reference) and [blog post](http://www.dataschool.io/python-quick-reference/)\n", 10 | "\n", 11 | "## Table of contents\n", 12 | "\n", 13 | "1. Imports\n", 14 | "2. Data Types\n", 15 | "3. Math\n", 16 | "4. Comparisons and Boolean Operations\n", 17 | "5. Conditional Statements\n", 18 | "6. Lists\n", 19 | "7. Tuples\n", 20 | "8. Strings\n", 21 | "9. Dictionaries\n", 22 | "10. Sets\n", 23 | "11. Defining Functions\n", 24 | "12. Anonymous (Lambda) Functions\n", 25 | "13. For Loops and While Loops\n", 26 | "14. Comprehensions\n", 27 | "15. Map and Filter" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "## 1. Imports" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 1, 40 | "metadata": { 41 | "collapsed": false 42 | }, 43 | "outputs": [ 44 | { 45 | "data": { 46 | "text/plain": [ 47 | "5.0" 48 | ] 49 | }, 50 | "execution_count": 1, 51 | "metadata": {}, 52 | "output_type": "execute_result" 53 | } 54 | ], 55 | "source": [ 56 | "# 'generic import' of math module\n", 57 | "import math\n", 58 | "math.sqrt(25)" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 2, 64 | "metadata": { 65 | "collapsed": false 66 | }, 67 | "outputs": [ 68 | { 69 | "data": { 70 | "text/plain": [ 71 | "5.0" 72 | ] 73 | }, 74 | "execution_count": 2, 75 | "metadata": {}, 76 | "output_type": "execute_result" 77 | } 78 | ], 79 | "source": [ 80 | "# import a function\n", 81 | "from math import sqrt\n", 82 | "sqrt(25) # no longer have to reference the module" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": 3, 88 | "metadata": { 89 | "collapsed": true 90 | }, 91 | "outputs": [], 92 | "source": [ 93 | "# import multiple functions at once\n", 94 | "from math import cos, floor" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 4, 100 | "metadata": { 101 | "collapsed": true 102 | }, 103 | "outputs": [], 104 | "source": [ 105 | "# import all functions in a module (generally discouraged)\n", 106 | "from csv import *" 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": 5, 112 | "metadata": { 113 | "collapsed": true 114 | }, 115 | "outputs": [], 116 | "source": [ 117 | "# define an alias\n", 118 | "import datetime as dt" 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": 6, 124 | "metadata": { 125 | "collapsed": false 126 | }, 127 | "outputs": [ 128 | { 129 | "name": "stdout", 130 | "output_type": "stream", 131 | "text": [ 132 | "['__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" 133 | ] 134 | } 135 | ], 136 | "source": [ 137 | "# show all functions in math module\n", 138 | "print(dir(math))" 139 | ] 140 | }, 141 | { 142 | "cell_type": "markdown", 143 | "metadata": {}, 144 | "source": [ 145 | "[Back to top]" 146 | ] 147 | }, 148 | { 149 | "cell_type": "markdown", 150 | "metadata": {}, 151 | "source": [ 152 | "## 2. Data Types\n", 153 | "\n", 154 | "**Determine the type of an object:**" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": 7, 160 | "metadata": { 161 | "collapsed": false 162 | }, 163 | "outputs": [ 164 | { 165 | "data": { 166 | "text/plain": [ 167 | "int" 168 | ] 169 | }, 170 | "execution_count": 7, 171 | "metadata": {}, 172 | "output_type": "execute_result" 173 | } 174 | ], 175 | "source": [ 176 | "type(2)" 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "execution_count": 8, 182 | "metadata": { 183 | "collapsed": false 184 | }, 185 | "outputs": [ 186 | { 187 | "data": { 188 | "text/plain": [ 189 | "float" 190 | ] 191 | }, 192 | "execution_count": 8, 193 | "metadata": {}, 194 | "output_type": "execute_result" 195 | } 196 | ], 197 | "source": [ 198 | "type(2.0)" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": 9, 204 | "metadata": { 205 | "collapsed": false 206 | }, 207 | "outputs": [ 208 | { 209 | "data": { 210 | "text/plain": [ 211 | "str" 212 | ] 213 | }, 214 | "execution_count": 9, 215 | "metadata": {}, 216 | "output_type": "execute_result" 217 | } 218 | ], 219 | "source": [ 220 | "type('two')" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": 10, 226 | "metadata": { 227 | "collapsed": false 228 | }, 229 | "outputs": [ 230 | { 231 | "data": { 232 | "text/plain": [ 233 | "bool" 234 | ] 235 | }, 236 | "execution_count": 10, 237 | "metadata": {}, 238 | "output_type": "execute_result" 239 | } 240 | ], 241 | "source": [ 242 | "type(True)" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": 11, 248 | "metadata": { 249 | "collapsed": false 250 | }, 251 | "outputs": [ 252 | { 253 | "data": { 254 | "text/plain": [ 255 | "NoneType" 256 | ] 257 | }, 258 | "execution_count": 11, 259 | "metadata": {}, 260 | "output_type": "execute_result" 261 | } 262 | ], 263 | "source": [ 264 | "type(None)" 265 | ] 266 | }, 267 | { 268 | "cell_type": "markdown", 269 | "metadata": {}, 270 | "source": [ 271 | "**Check if an object is of a given type:**" 272 | ] 273 | }, 274 | { 275 | "cell_type": "code", 276 | "execution_count": 12, 277 | "metadata": { 278 | "collapsed": false 279 | }, 280 | "outputs": [ 281 | { 282 | "data": { 283 | "text/plain": [ 284 | "False" 285 | ] 286 | }, 287 | "execution_count": 12, 288 | "metadata": {}, 289 | "output_type": "execute_result" 290 | } 291 | ], 292 | "source": [ 293 | "isinstance(2.0, int)" 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": 13, 299 | "metadata": { 300 | "collapsed": false 301 | }, 302 | "outputs": [ 303 | { 304 | "data": { 305 | "text/plain": [ 306 | "True" 307 | ] 308 | }, 309 | "execution_count": 13, 310 | "metadata": {}, 311 | "output_type": "execute_result" 312 | } 313 | ], 314 | "source": [ 315 | "isinstance(2.0, (int, float))" 316 | ] 317 | }, 318 | { 319 | "cell_type": "markdown", 320 | "metadata": {}, 321 | "source": [ 322 | "**Convert an object to a given type:**" 323 | ] 324 | }, 325 | { 326 | "cell_type": "code", 327 | "execution_count": 14, 328 | "metadata": { 329 | "collapsed": false 330 | }, 331 | "outputs": [ 332 | { 333 | "data": { 334 | "text/plain": [ 335 | "2.0" 336 | ] 337 | }, 338 | "execution_count": 14, 339 | "metadata": {}, 340 | "output_type": "execute_result" 341 | } 342 | ], 343 | "source": [ 344 | "float(2)" 345 | ] 346 | }, 347 | { 348 | "cell_type": "code", 349 | "execution_count": 15, 350 | "metadata": { 351 | "collapsed": false 352 | }, 353 | "outputs": [ 354 | { 355 | "data": { 356 | "text/plain": [ 357 | "2" 358 | ] 359 | }, 360 | "execution_count": 15, 361 | "metadata": {}, 362 | "output_type": "execute_result" 363 | } 364 | ], 365 | "source": [ 366 | "int(2.9)" 367 | ] 368 | }, 369 | { 370 | "cell_type": "code", 371 | "execution_count": 16, 372 | "metadata": { 373 | "collapsed": false 374 | }, 375 | "outputs": [ 376 | { 377 | "data": { 378 | "text/plain": [ 379 | "'2.9'" 380 | ] 381 | }, 382 | "execution_count": 16, 383 | "metadata": {}, 384 | "output_type": "execute_result" 385 | } 386 | ], 387 | "source": [ 388 | "str(2.9)" 389 | ] 390 | }, 391 | { 392 | "cell_type": "markdown", 393 | "metadata": {}, 394 | "source": [ 395 | "**Zero, `None`, and empty containers are converted to `False`:**" 396 | ] 397 | }, 398 | { 399 | "cell_type": "code", 400 | "execution_count": 17, 401 | "metadata": { 402 | "collapsed": false 403 | }, 404 | "outputs": [ 405 | { 406 | "data": { 407 | "text/plain": [ 408 | "False" 409 | ] 410 | }, 411 | "execution_count": 17, 412 | "metadata": {}, 413 | "output_type": "execute_result" 414 | } 415 | ], 416 | "source": [ 417 | "bool(0)" 418 | ] 419 | }, 420 | { 421 | "cell_type": "code", 422 | "execution_count": 18, 423 | "metadata": { 424 | "collapsed": false 425 | }, 426 | "outputs": [ 427 | { 428 | "data": { 429 | "text/plain": [ 430 | "False" 431 | ] 432 | }, 433 | "execution_count": 18, 434 | "metadata": {}, 435 | "output_type": "execute_result" 436 | } 437 | ], 438 | "source": [ 439 | "bool(None)" 440 | ] 441 | }, 442 | { 443 | "cell_type": "code", 444 | "execution_count": 19, 445 | "metadata": { 446 | "collapsed": false 447 | }, 448 | "outputs": [ 449 | { 450 | "data": { 451 | "text/plain": [ 452 | "False" 453 | ] 454 | }, 455 | "execution_count": 19, 456 | "metadata": {}, 457 | "output_type": "execute_result" 458 | } 459 | ], 460 | "source": [ 461 | "bool('') # empty string" 462 | ] 463 | }, 464 | { 465 | "cell_type": "code", 466 | "execution_count": 20, 467 | "metadata": { 468 | "collapsed": false 469 | }, 470 | "outputs": [ 471 | { 472 | "data": { 473 | "text/plain": [ 474 | "False" 475 | ] 476 | }, 477 | "execution_count": 20, 478 | "metadata": {}, 479 | "output_type": "execute_result" 480 | } 481 | ], 482 | "source": [ 483 | "bool([]) # empty list" 484 | ] 485 | }, 486 | { 487 | "cell_type": "code", 488 | "execution_count": 21, 489 | "metadata": { 490 | "collapsed": false 491 | }, 492 | "outputs": [ 493 | { 494 | "data": { 495 | "text/plain": [ 496 | "False" 497 | ] 498 | }, 499 | "execution_count": 21, 500 | "metadata": {}, 501 | "output_type": "execute_result" 502 | } 503 | ], 504 | "source": [ 505 | "bool({}) # empty dictionary" 506 | ] 507 | }, 508 | { 509 | "cell_type": "markdown", 510 | "metadata": {}, 511 | "source": [ 512 | "**Non-empty containers and non-zeros are converted to `True`:**" 513 | ] 514 | }, 515 | { 516 | "cell_type": "code", 517 | "execution_count": 22, 518 | "metadata": { 519 | "collapsed": false 520 | }, 521 | "outputs": [ 522 | { 523 | "data": { 524 | "text/plain": [ 525 | "True" 526 | ] 527 | }, 528 | "execution_count": 22, 529 | "metadata": {}, 530 | "output_type": "execute_result" 531 | } 532 | ], 533 | "source": [ 534 | "bool(2)" 535 | ] 536 | }, 537 | { 538 | "cell_type": "code", 539 | "execution_count": 23, 540 | "metadata": { 541 | "collapsed": false 542 | }, 543 | "outputs": [ 544 | { 545 | "data": { 546 | "text/plain": [ 547 | "True" 548 | ] 549 | }, 550 | "execution_count": 23, 551 | "metadata": {}, 552 | "output_type": "execute_result" 553 | } 554 | ], 555 | "source": [ 556 | "bool('two')" 557 | ] 558 | }, 559 | { 560 | "cell_type": "code", 561 | "execution_count": 24, 562 | "metadata": { 563 | "collapsed": false 564 | }, 565 | "outputs": [ 566 | { 567 | "data": { 568 | "text/plain": [ 569 | "True" 570 | ] 571 | }, 572 | "execution_count": 24, 573 | "metadata": {}, 574 | "output_type": "execute_result" 575 | } 576 | ], 577 | "source": [ 578 | "bool([2])" 579 | ] 580 | }, 581 | { 582 | "cell_type": "markdown", 583 | "metadata": {}, 584 | "source": [ 585 | "[Back to top]" 586 | ] 587 | }, 588 | { 589 | "cell_type": "markdown", 590 | "metadata": {}, 591 | "source": [ 592 | "## 3. Math" 593 | ] 594 | }, 595 | { 596 | "cell_type": "code", 597 | "execution_count": 25, 598 | "metadata": { 599 | "collapsed": false 600 | }, 601 | "outputs": [ 602 | { 603 | "data": { 604 | "text/plain": [ 605 | "14" 606 | ] 607 | }, 608 | "execution_count": 25, 609 | "metadata": {}, 610 | "output_type": "execute_result" 611 | } 612 | ], 613 | "source": [ 614 | "10 + 4" 615 | ] 616 | }, 617 | { 618 | "cell_type": "code", 619 | "execution_count": 26, 620 | "metadata": { 621 | "collapsed": false 622 | }, 623 | "outputs": [ 624 | { 625 | "data": { 626 | "text/plain": [ 627 | "6" 628 | ] 629 | }, 630 | "execution_count": 26, 631 | "metadata": {}, 632 | "output_type": "execute_result" 633 | } 634 | ], 635 | "source": [ 636 | "10 - 4" 637 | ] 638 | }, 639 | { 640 | "cell_type": "code", 641 | "execution_count": 27, 642 | "metadata": { 643 | "collapsed": false 644 | }, 645 | "outputs": [ 646 | { 647 | "data": { 648 | "text/plain": [ 649 | "40" 650 | ] 651 | }, 652 | "execution_count": 27, 653 | "metadata": {}, 654 | "output_type": "execute_result" 655 | } 656 | ], 657 | "source": [ 658 | "10 * 4" 659 | ] 660 | }, 661 | { 662 | "cell_type": "code", 663 | "execution_count": 28, 664 | "metadata": { 665 | "collapsed": false 666 | }, 667 | "outputs": [ 668 | { 669 | "data": { 670 | "text/plain": [ 671 | "10000" 672 | ] 673 | }, 674 | "execution_count": 28, 675 | "metadata": {}, 676 | "output_type": "execute_result" 677 | } 678 | ], 679 | "source": [ 680 | "10 ** 4 # exponent" 681 | ] 682 | }, 683 | { 684 | "cell_type": "code", 685 | "execution_count": 29, 686 | "metadata": { 687 | "collapsed": false 688 | }, 689 | "outputs": [ 690 | { 691 | "data": { 692 | "text/plain": [ 693 | "1" 694 | ] 695 | }, 696 | "execution_count": 29, 697 | "metadata": {}, 698 | "output_type": "execute_result" 699 | } 700 | ], 701 | "source": [ 702 | "5 % 4 # modulo - computes the remainder" 703 | ] 704 | }, 705 | { 706 | "cell_type": "code", 707 | "execution_count": 30, 708 | "metadata": { 709 | "collapsed": false, 710 | "scrolled": true 711 | }, 712 | "outputs": [ 713 | { 714 | "data": { 715 | "text/plain": [ 716 | "2" 717 | ] 718 | }, 719 | "execution_count": 30, 720 | "metadata": {}, 721 | "output_type": "execute_result" 722 | } 723 | ], 724 | "source": [ 725 | "# Python 2: returns 2 (because both types are 'int')\n", 726 | "# Python 3: returns 2.5\n", 727 | "10 / 4" 728 | ] 729 | }, 730 | { 731 | "cell_type": "code", 732 | "execution_count": 31, 733 | "metadata": { 734 | "collapsed": false, 735 | "scrolled": true 736 | }, 737 | "outputs": [ 738 | { 739 | "data": { 740 | "text/plain": [ 741 | "2.5" 742 | ] 743 | }, 744 | "execution_count": 31, 745 | "metadata": {}, 746 | "output_type": "execute_result" 747 | } 748 | ], 749 | "source": [ 750 | "10 / float(4)" 751 | ] 752 | }, 753 | { 754 | "cell_type": "code", 755 | "execution_count": 32, 756 | "metadata": { 757 | "collapsed": true 758 | }, 759 | "outputs": [], 760 | "source": [ 761 | "# force '/' in Python 2 to perform 'true division' (unnecessary in Python 3)\n", 762 | "from __future__ import division" 763 | ] 764 | }, 765 | { 766 | "cell_type": "code", 767 | "execution_count": 33, 768 | "metadata": { 769 | "collapsed": false 770 | }, 771 | "outputs": [ 772 | { 773 | "data": { 774 | "text/plain": [ 775 | "2.5" 776 | ] 777 | }, 778 | "execution_count": 33, 779 | "metadata": {}, 780 | "output_type": "execute_result" 781 | } 782 | ], 783 | "source": [ 784 | "10 / 4 # true division" 785 | ] 786 | }, 787 | { 788 | "cell_type": "code", 789 | "execution_count": 34, 790 | "metadata": { 791 | "collapsed": false 792 | }, 793 | "outputs": [ 794 | { 795 | "data": { 796 | "text/plain": [ 797 | "2" 798 | ] 799 | }, 800 | "execution_count": 34, 801 | "metadata": {}, 802 | "output_type": "execute_result" 803 | } 804 | ], 805 | "source": [ 806 | "10 // 4 # floor division" 807 | ] 808 | }, 809 | { 810 | "cell_type": "markdown", 811 | "metadata": {}, 812 | "source": [ 813 | "[Back to top]" 814 | ] 815 | }, 816 | { 817 | "cell_type": "markdown", 818 | "metadata": {}, 819 | "source": [ 820 | "## 4. Comparisons and Boolean Operations" 821 | ] 822 | }, 823 | { 824 | "cell_type": "markdown", 825 | "metadata": {}, 826 | "source": [ 827 | "**Assignment statement:**" 828 | ] 829 | }, 830 | { 831 | "cell_type": "code", 832 | "execution_count": 35, 833 | "metadata": { 834 | "collapsed": true 835 | }, 836 | "outputs": [], 837 | "source": [ 838 | "x = 5" 839 | ] 840 | }, 841 | { 842 | "cell_type": "markdown", 843 | "metadata": {}, 844 | "source": [ 845 | "**Comparisons:**" 846 | ] 847 | }, 848 | { 849 | "cell_type": "code", 850 | "execution_count": 36, 851 | "metadata": { 852 | "collapsed": false 853 | }, 854 | "outputs": [ 855 | { 856 | "data": { 857 | "text/plain": [ 858 | "True" 859 | ] 860 | }, 861 | "execution_count": 36, 862 | "metadata": {}, 863 | "output_type": "execute_result" 864 | } 865 | ], 866 | "source": [ 867 | "x > 3" 868 | ] 869 | }, 870 | { 871 | "cell_type": "code", 872 | "execution_count": 37, 873 | "metadata": { 874 | "collapsed": false 875 | }, 876 | "outputs": [ 877 | { 878 | "data": { 879 | "text/plain": [ 880 | "True" 881 | ] 882 | }, 883 | "execution_count": 37, 884 | "metadata": {}, 885 | "output_type": "execute_result" 886 | } 887 | ], 888 | "source": [ 889 | "x >= 3" 890 | ] 891 | }, 892 | { 893 | "cell_type": "code", 894 | "execution_count": 38, 895 | "metadata": { 896 | "collapsed": false 897 | }, 898 | "outputs": [ 899 | { 900 | "data": { 901 | "text/plain": [ 902 | "True" 903 | ] 904 | }, 905 | "execution_count": 38, 906 | "metadata": {}, 907 | "output_type": "execute_result" 908 | } 909 | ], 910 | "source": [ 911 | "x != 3" 912 | ] 913 | }, 914 | { 915 | "cell_type": "code", 916 | "execution_count": 39, 917 | "metadata": { 918 | "collapsed": false 919 | }, 920 | "outputs": [ 921 | { 922 | "data": { 923 | "text/plain": [ 924 | "True" 925 | ] 926 | }, 927 | "execution_count": 39, 928 | "metadata": {}, 929 | "output_type": "execute_result" 930 | } 931 | ], 932 | "source": [ 933 | "x == 5" 934 | ] 935 | }, 936 | { 937 | "cell_type": "markdown", 938 | "metadata": {}, 939 | "source": [ 940 | "**Boolean operations:**" 941 | ] 942 | }, 943 | { 944 | "cell_type": "code", 945 | "execution_count": 40, 946 | "metadata": { 947 | "collapsed": false 948 | }, 949 | "outputs": [ 950 | { 951 | "data": { 952 | "text/plain": [ 953 | "True" 954 | ] 955 | }, 956 | "execution_count": 40, 957 | "metadata": {}, 958 | "output_type": "execute_result" 959 | } 960 | ], 961 | "source": [ 962 | "5 > 3 and 6 > 3" 963 | ] 964 | }, 965 | { 966 | "cell_type": "code", 967 | "execution_count": 41, 968 | "metadata": { 969 | "collapsed": false 970 | }, 971 | "outputs": [ 972 | { 973 | "data": { 974 | "text/plain": [ 975 | "True" 976 | ] 977 | }, 978 | "execution_count": 41, 979 | "metadata": {}, 980 | "output_type": "execute_result" 981 | } 982 | ], 983 | "source": [ 984 | "5 > 3 or 5 < 3" 985 | ] 986 | }, 987 | { 988 | "cell_type": "code", 989 | "execution_count": 42, 990 | "metadata": { 991 | "collapsed": false 992 | }, 993 | "outputs": [ 994 | { 995 | "data": { 996 | "text/plain": [ 997 | "True" 998 | ] 999 | }, 1000 | "execution_count": 42, 1001 | "metadata": {}, 1002 | "output_type": "execute_result" 1003 | } 1004 | ], 1005 | "source": [ 1006 | "not False" 1007 | ] 1008 | }, 1009 | { 1010 | "cell_type": "code", 1011 | "execution_count": 43, 1012 | "metadata": { 1013 | "collapsed": false 1014 | }, 1015 | "outputs": [ 1016 | { 1017 | "data": { 1018 | "text/plain": [ 1019 | "True" 1020 | ] 1021 | }, 1022 | "execution_count": 43, 1023 | "metadata": {}, 1024 | "output_type": "execute_result" 1025 | } 1026 | ], 1027 | "source": [ 1028 | "False or not False and True # evaluation order: not, and, or" 1029 | ] 1030 | }, 1031 | { 1032 | "cell_type": "markdown", 1033 | "metadata": {}, 1034 | "source": [ 1035 | "[Back to top]" 1036 | ] 1037 | }, 1038 | { 1039 | "cell_type": "markdown", 1040 | "metadata": {}, 1041 | "source": [ 1042 | "## 5. Conditional Statements" 1043 | ] 1044 | }, 1045 | { 1046 | "cell_type": "code", 1047 | "execution_count": 44, 1048 | "metadata": { 1049 | "collapsed": false 1050 | }, 1051 | "outputs": [ 1052 | { 1053 | "name": "stdout", 1054 | "output_type": "stream", 1055 | "text": [ 1056 | "positive\n" 1057 | ] 1058 | } 1059 | ], 1060 | "source": [ 1061 | "# if statement\n", 1062 | "if x > 0:\n", 1063 | " print('positive')" 1064 | ] 1065 | }, 1066 | { 1067 | "cell_type": "code", 1068 | "execution_count": 45, 1069 | "metadata": { 1070 | "collapsed": false 1071 | }, 1072 | "outputs": [ 1073 | { 1074 | "name": "stdout", 1075 | "output_type": "stream", 1076 | "text": [ 1077 | "positive\n" 1078 | ] 1079 | } 1080 | ], 1081 | "source": [ 1082 | "# if/else statement\n", 1083 | "if x > 0:\n", 1084 | " print('positive')\n", 1085 | "else:\n", 1086 | " print('zero or negative')" 1087 | ] 1088 | }, 1089 | { 1090 | "cell_type": "code", 1091 | "execution_count": 46, 1092 | "metadata": { 1093 | "collapsed": false 1094 | }, 1095 | "outputs": [ 1096 | { 1097 | "name": "stdout", 1098 | "output_type": "stream", 1099 | "text": [ 1100 | "positive\n" 1101 | ] 1102 | } 1103 | ], 1104 | "source": [ 1105 | "# if/elif/else statement\n", 1106 | "if x > 0:\n", 1107 | " print('positive')\n", 1108 | "elif x == 0:\n", 1109 | " print('zero')\n", 1110 | "else:\n", 1111 | " print('negative')" 1112 | ] 1113 | }, 1114 | { 1115 | "cell_type": "code", 1116 | "execution_count": 47, 1117 | "metadata": { 1118 | "collapsed": false 1119 | }, 1120 | "outputs": [ 1121 | { 1122 | "name": "stdout", 1123 | "output_type": "stream", 1124 | "text": [ 1125 | "positive\n" 1126 | ] 1127 | } 1128 | ], 1129 | "source": [ 1130 | "# single-line if statement (sometimes discouraged)\n", 1131 | "if x > 0: print('positive')" 1132 | ] 1133 | }, 1134 | { 1135 | "cell_type": "code", 1136 | "execution_count": 48, 1137 | "metadata": { 1138 | "collapsed": false 1139 | }, 1140 | "outputs": [ 1141 | { 1142 | "data": { 1143 | "text/plain": [ 1144 | "'positive'" 1145 | ] 1146 | }, 1147 | "execution_count": 48, 1148 | "metadata": {}, 1149 | "output_type": "execute_result" 1150 | } 1151 | ], 1152 | "source": [ 1153 | "# single-line if/else statement (sometimes discouraged), known as a 'ternary operator'\n", 1154 | "'positive' if x > 0 else 'zero or negative'" 1155 | ] 1156 | }, 1157 | { 1158 | "cell_type": "markdown", 1159 | "metadata": {}, 1160 | "source": [ 1161 | "[Back to top]" 1162 | ] 1163 | }, 1164 | { 1165 | "cell_type": "markdown", 1166 | "metadata": {}, 1167 | "source": [ 1168 | "## 6. Lists\n", 1169 | "\n", 1170 | "- **List properties:** ordered, iterable, mutable, can contain multiple data types" 1171 | ] 1172 | }, 1173 | { 1174 | "cell_type": "code", 1175 | "execution_count": 49, 1176 | "metadata": { 1177 | "collapsed": true 1178 | }, 1179 | "outputs": [], 1180 | "source": [ 1181 | "# create an empty list (two ways)\n", 1182 | "empty_list = []\n", 1183 | "empty_list = list()" 1184 | ] 1185 | }, 1186 | { 1187 | "cell_type": "code", 1188 | "execution_count": 50, 1189 | "metadata": { 1190 | "collapsed": true 1191 | }, 1192 | "outputs": [], 1193 | "source": [ 1194 | "# create a list\n", 1195 | "simpsons = ['homer', 'marge', 'bart']" 1196 | ] 1197 | }, 1198 | { 1199 | "cell_type": "markdown", 1200 | "metadata": {}, 1201 | "source": [ 1202 | "**Examine a list:**" 1203 | ] 1204 | }, 1205 | { 1206 | "cell_type": "code", 1207 | "execution_count": 51, 1208 | "metadata": { 1209 | "collapsed": false 1210 | }, 1211 | "outputs": [ 1212 | { 1213 | "data": { 1214 | "text/plain": [ 1215 | "'homer'" 1216 | ] 1217 | }, 1218 | "execution_count": 51, 1219 | "metadata": {}, 1220 | "output_type": "execute_result" 1221 | } 1222 | ], 1223 | "source": [ 1224 | "# print element 0\n", 1225 | "simpsons[0]" 1226 | ] 1227 | }, 1228 | { 1229 | "cell_type": "code", 1230 | "execution_count": 52, 1231 | "metadata": { 1232 | "collapsed": false 1233 | }, 1234 | "outputs": [ 1235 | { 1236 | "data": { 1237 | "text/plain": [ 1238 | "3" 1239 | ] 1240 | }, 1241 | "execution_count": 52, 1242 | "metadata": {}, 1243 | "output_type": "execute_result" 1244 | } 1245 | ], 1246 | "source": [ 1247 | "len(simpsons)" 1248 | ] 1249 | }, 1250 | { 1251 | "cell_type": "markdown", 1252 | "metadata": {}, 1253 | "source": [ 1254 | "**Modify a list (does not return the list):**" 1255 | ] 1256 | }, 1257 | { 1258 | "cell_type": "code", 1259 | "execution_count": 53, 1260 | "metadata": { 1261 | "collapsed": false 1262 | }, 1263 | "outputs": [ 1264 | { 1265 | "data": { 1266 | "text/plain": [ 1267 | "['homer', 'marge', 'bart', 'lisa']" 1268 | ] 1269 | }, 1270 | "execution_count": 53, 1271 | "metadata": {}, 1272 | "output_type": "execute_result" 1273 | } 1274 | ], 1275 | "source": [ 1276 | "# append element to end\n", 1277 | "simpsons.append('lisa')\n", 1278 | "simpsons" 1279 | ] 1280 | }, 1281 | { 1282 | "cell_type": "code", 1283 | "execution_count": 54, 1284 | "metadata": { 1285 | "collapsed": false 1286 | }, 1287 | "outputs": [ 1288 | { 1289 | "data": { 1290 | "text/plain": [ 1291 | "['homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']" 1292 | ] 1293 | }, 1294 | "execution_count": 54, 1295 | "metadata": {}, 1296 | "output_type": "execute_result" 1297 | } 1298 | ], 1299 | "source": [ 1300 | "# append multiple elements to end\n", 1301 | "simpsons.extend(['itchy', 'scratchy'])\n", 1302 | "simpsons" 1303 | ] 1304 | }, 1305 | { 1306 | "cell_type": "code", 1307 | "execution_count": 55, 1308 | "metadata": { 1309 | "collapsed": false 1310 | }, 1311 | "outputs": [ 1312 | { 1313 | "data": { 1314 | "text/plain": [ 1315 | "['maggie', 'homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']" 1316 | ] 1317 | }, 1318 | "execution_count": 55, 1319 | "metadata": {}, 1320 | "output_type": "execute_result" 1321 | } 1322 | ], 1323 | "source": [ 1324 | "# insert element at index 0 (shifts everything right)\n", 1325 | "simpsons.insert(0, 'maggie')\n", 1326 | "simpsons" 1327 | ] 1328 | }, 1329 | { 1330 | "cell_type": "code", 1331 | "execution_count": 56, 1332 | "metadata": { 1333 | "collapsed": false 1334 | }, 1335 | "outputs": [ 1336 | { 1337 | "data": { 1338 | "text/plain": [ 1339 | "['maggie', 'homer', 'marge', 'lisa', 'itchy', 'scratchy']" 1340 | ] 1341 | }, 1342 | "execution_count": 56, 1343 | "metadata": {}, 1344 | "output_type": "execute_result" 1345 | } 1346 | ], 1347 | "source": [ 1348 | "# search for first instance and remove it\n", 1349 | "simpsons.remove('bart')\n", 1350 | "simpsons" 1351 | ] 1352 | }, 1353 | { 1354 | "cell_type": "code", 1355 | "execution_count": 57, 1356 | "metadata": { 1357 | "collapsed": false 1358 | }, 1359 | "outputs": [ 1360 | { 1361 | "data": { 1362 | "text/plain": [ 1363 | "'maggie'" 1364 | ] 1365 | }, 1366 | "execution_count": 57, 1367 | "metadata": {}, 1368 | "output_type": "execute_result" 1369 | } 1370 | ], 1371 | "source": [ 1372 | "# remove element 0 and return it\n", 1373 | "simpsons.pop(0)" 1374 | ] 1375 | }, 1376 | { 1377 | "cell_type": "code", 1378 | "execution_count": 58, 1379 | "metadata": { 1380 | "collapsed": false 1381 | }, 1382 | "outputs": [ 1383 | { 1384 | "data": { 1385 | "text/plain": [ 1386 | "['marge', 'lisa', 'itchy', 'scratchy']" 1387 | ] 1388 | }, 1389 | "execution_count": 58, 1390 | "metadata": {}, 1391 | "output_type": "execute_result" 1392 | } 1393 | ], 1394 | "source": [ 1395 | "# remove element 0 (does not return it)\n", 1396 | "del simpsons[0]\n", 1397 | "simpsons" 1398 | ] 1399 | }, 1400 | { 1401 | "cell_type": "code", 1402 | "execution_count": 59, 1403 | "metadata": { 1404 | "collapsed": false 1405 | }, 1406 | "outputs": [ 1407 | { 1408 | "data": { 1409 | "text/plain": [ 1410 | "['krusty', 'lisa', 'itchy', 'scratchy']" 1411 | ] 1412 | }, 1413 | "execution_count": 59, 1414 | "metadata": {}, 1415 | "output_type": "execute_result" 1416 | } 1417 | ], 1418 | "source": [ 1419 | "# replace element 0\n", 1420 | "simpsons[0] = 'krusty'\n", 1421 | "simpsons" 1422 | ] 1423 | }, 1424 | { 1425 | "cell_type": "code", 1426 | "execution_count": 60, 1427 | "metadata": { 1428 | "collapsed": false 1429 | }, 1430 | "outputs": [ 1431 | { 1432 | "data": { 1433 | "text/plain": [ 1434 | "['krusty', 'lisa', 'itchy', 'scratchy', 'ned', 'rod', 'todd']" 1435 | ] 1436 | }, 1437 | "execution_count": 60, 1438 | "metadata": {}, 1439 | "output_type": "execute_result" 1440 | } 1441 | ], 1442 | "source": [ 1443 | "# concatenate lists (slower than 'extend' method)\n", 1444 | "neighbors = simpsons + ['ned', 'rod', 'todd']\n", 1445 | "neighbors" 1446 | ] 1447 | }, 1448 | { 1449 | "cell_type": "markdown", 1450 | "metadata": {}, 1451 | "source": [ 1452 | "**Find elements in a list:**" 1453 | ] 1454 | }, 1455 | { 1456 | "cell_type": "code", 1457 | "execution_count": 61, 1458 | "metadata": { 1459 | "collapsed": false 1460 | }, 1461 | "outputs": [ 1462 | { 1463 | "data": { 1464 | "text/plain": [ 1465 | "1" 1466 | ] 1467 | }, 1468 | "execution_count": 61, 1469 | "metadata": {}, 1470 | "output_type": "execute_result" 1471 | } 1472 | ], 1473 | "source": [ 1474 | "# counts the number of instances\n", 1475 | "simpsons.count('lisa')" 1476 | ] 1477 | }, 1478 | { 1479 | "cell_type": "code", 1480 | "execution_count": 62, 1481 | "metadata": { 1482 | "collapsed": false 1483 | }, 1484 | "outputs": [ 1485 | { 1486 | "data": { 1487 | "text/plain": [ 1488 | "2" 1489 | ] 1490 | }, 1491 | "execution_count": 62, 1492 | "metadata": {}, 1493 | "output_type": "execute_result" 1494 | } 1495 | ], 1496 | "source": [ 1497 | "# returns index of first instance\n", 1498 | "simpsons.index('itchy')" 1499 | ] 1500 | }, 1501 | { 1502 | "cell_type": "markdown", 1503 | "metadata": {}, 1504 | "source": [ 1505 | "**List slicing:**" 1506 | ] 1507 | }, 1508 | { 1509 | "cell_type": "code", 1510 | "execution_count": 63, 1511 | "metadata": { 1512 | "collapsed": true 1513 | }, 1514 | "outputs": [], 1515 | "source": [ 1516 | "weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']" 1517 | ] 1518 | }, 1519 | { 1520 | "cell_type": "code", 1521 | "execution_count": 64, 1522 | "metadata": { 1523 | "collapsed": false 1524 | }, 1525 | "outputs": [ 1526 | { 1527 | "data": { 1528 | "text/plain": [ 1529 | "'mon'" 1530 | ] 1531 | }, 1532 | "execution_count": 64, 1533 | "metadata": {}, 1534 | "output_type": "execute_result" 1535 | } 1536 | ], 1537 | "source": [ 1538 | "# element 0\n", 1539 | "weekdays[0]" 1540 | ] 1541 | }, 1542 | { 1543 | "cell_type": "code", 1544 | "execution_count": 65, 1545 | "metadata": { 1546 | "collapsed": false 1547 | }, 1548 | "outputs": [ 1549 | { 1550 | "data": { 1551 | "text/plain": [ 1552 | "['mon', 'tues', 'wed']" 1553 | ] 1554 | }, 1555 | "execution_count": 65, 1556 | "metadata": {}, 1557 | "output_type": "execute_result" 1558 | } 1559 | ], 1560 | "source": [ 1561 | "# elements 0 (inclusive) to 3 (exclusive)\n", 1562 | "weekdays[0:3]" 1563 | ] 1564 | }, 1565 | { 1566 | "cell_type": "code", 1567 | "execution_count": 66, 1568 | "metadata": { 1569 | "collapsed": false 1570 | }, 1571 | "outputs": [ 1572 | { 1573 | "data": { 1574 | "text/plain": [ 1575 | "['mon', 'tues', 'wed']" 1576 | ] 1577 | }, 1578 | "execution_count": 66, 1579 | "metadata": {}, 1580 | "output_type": "execute_result" 1581 | } 1582 | ], 1583 | "source": [ 1584 | "# starting point is implied to be 0\n", 1585 | "weekdays[:3]" 1586 | ] 1587 | }, 1588 | { 1589 | "cell_type": "code", 1590 | "execution_count": 67, 1591 | "metadata": { 1592 | "collapsed": false 1593 | }, 1594 | "outputs": [ 1595 | { 1596 | "data": { 1597 | "text/plain": [ 1598 | "['thurs', 'fri']" 1599 | ] 1600 | }, 1601 | "execution_count": 67, 1602 | "metadata": {}, 1603 | "output_type": "execute_result" 1604 | } 1605 | ], 1606 | "source": [ 1607 | "# elements 3 (inclusive) through the end\n", 1608 | "weekdays[3:]" 1609 | ] 1610 | }, 1611 | { 1612 | "cell_type": "code", 1613 | "execution_count": 68, 1614 | "metadata": { 1615 | "collapsed": false 1616 | }, 1617 | "outputs": [ 1618 | { 1619 | "data": { 1620 | "text/plain": [ 1621 | "'fri'" 1622 | ] 1623 | }, 1624 | "execution_count": 68, 1625 | "metadata": {}, 1626 | "output_type": "execute_result" 1627 | } 1628 | ], 1629 | "source": [ 1630 | "# last element\n", 1631 | "weekdays[-1]" 1632 | ] 1633 | }, 1634 | { 1635 | "cell_type": "code", 1636 | "execution_count": 69, 1637 | "metadata": { 1638 | "collapsed": false 1639 | }, 1640 | "outputs": [ 1641 | { 1642 | "data": { 1643 | "text/plain": [ 1644 | "['mon', 'wed', 'fri']" 1645 | ] 1646 | }, 1647 | "execution_count": 69, 1648 | "metadata": {}, 1649 | "output_type": "execute_result" 1650 | } 1651 | ], 1652 | "source": [ 1653 | "# every 2nd element (step by 2)\n", 1654 | "weekdays[::2]" 1655 | ] 1656 | }, 1657 | { 1658 | "cell_type": "code", 1659 | "execution_count": 70, 1660 | "metadata": { 1661 | "collapsed": false 1662 | }, 1663 | "outputs": [ 1664 | { 1665 | "data": { 1666 | "text/plain": [ 1667 | "['fri', 'thurs', 'wed', 'tues', 'mon']" 1668 | ] 1669 | }, 1670 | "execution_count": 70, 1671 | "metadata": {}, 1672 | "output_type": "execute_result" 1673 | } 1674 | ], 1675 | "source": [ 1676 | "# backwards (step by -1)\n", 1677 | "weekdays[::-1]" 1678 | ] 1679 | }, 1680 | { 1681 | "cell_type": "code", 1682 | "execution_count": 71, 1683 | "metadata": { 1684 | "collapsed": false 1685 | }, 1686 | "outputs": [ 1687 | { 1688 | "data": { 1689 | "text/plain": [ 1690 | "['fri', 'thurs', 'wed', 'tues', 'mon']" 1691 | ] 1692 | }, 1693 | "execution_count": 71, 1694 | "metadata": {}, 1695 | "output_type": "execute_result" 1696 | } 1697 | ], 1698 | "source": [ 1699 | "# alternative method for returning the list backwards\n", 1700 | "list(reversed(weekdays))" 1701 | ] 1702 | }, 1703 | { 1704 | "cell_type": "markdown", 1705 | "metadata": {}, 1706 | "source": [ 1707 | "**Sort a list in place (modifies but does not return the list):**" 1708 | ] 1709 | }, 1710 | { 1711 | "cell_type": "code", 1712 | "execution_count": 72, 1713 | "metadata": { 1714 | "collapsed": false 1715 | }, 1716 | "outputs": [ 1717 | { 1718 | "data": { 1719 | "text/plain": [ 1720 | "['itchy', 'krusty', 'lisa', 'scratchy']" 1721 | ] 1722 | }, 1723 | "execution_count": 72, 1724 | "metadata": {}, 1725 | "output_type": "execute_result" 1726 | } 1727 | ], 1728 | "source": [ 1729 | "simpsons.sort()\n", 1730 | "simpsons" 1731 | ] 1732 | }, 1733 | { 1734 | "cell_type": "code", 1735 | "execution_count": 73, 1736 | "metadata": { 1737 | "collapsed": false 1738 | }, 1739 | "outputs": [ 1740 | { 1741 | "data": { 1742 | "text/plain": [ 1743 | "['scratchy', 'lisa', 'krusty', 'itchy']" 1744 | ] 1745 | }, 1746 | "execution_count": 73, 1747 | "metadata": {}, 1748 | "output_type": "execute_result" 1749 | } 1750 | ], 1751 | "source": [ 1752 | "# sort in reverse\n", 1753 | "simpsons.sort(reverse=True)\n", 1754 | "simpsons" 1755 | ] 1756 | }, 1757 | { 1758 | "cell_type": "code", 1759 | "execution_count": 74, 1760 | "metadata": { 1761 | "collapsed": false 1762 | }, 1763 | "outputs": [ 1764 | { 1765 | "data": { 1766 | "text/plain": [ 1767 | "['lisa', 'itchy', 'krusty', 'scratchy']" 1768 | ] 1769 | }, 1770 | "execution_count": 74, 1771 | "metadata": {}, 1772 | "output_type": "execute_result" 1773 | } 1774 | ], 1775 | "source": [ 1776 | "# sort by a key\n", 1777 | "simpsons.sort(key=len)\n", 1778 | "simpsons" 1779 | ] 1780 | }, 1781 | { 1782 | "cell_type": "markdown", 1783 | "metadata": {}, 1784 | "source": [ 1785 | "**Return a sorted list (does not modify the original list):**" 1786 | ] 1787 | }, 1788 | { 1789 | "cell_type": "code", 1790 | "execution_count": 75, 1791 | "metadata": { 1792 | "collapsed": false 1793 | }, 1794 | "outputs": [ 1795 | { 1796 | "data": { 1797 | "text/plain": [ 1798 | "['itchy', 'krusty', 'lisa', 'scratchy']" 1799 | ] 1800 | }, 1801 | "execution_count": 75, 1802 | "metadata": {}, 1803 | "output_type": "execute_result" 1804 | } 1805 | ], 1806 | "source": [ 1807 | "sorted(simpsons)" 1808 | ] 1809 | }, 1810 | { 1811 | "cell_type": "code", 1812 | "execution_count": 76, 1813 | "metadata": { 1814 | "collapsed": false 1815 | }, 1816 | "outputs": [ 1817 | { 1818 | "data": { 1819 | "text/plain": [ 1820 | "['scratchy', 'lisa', 'krusty', 'itchy']" 1821 | ] 1822 | }, 1823 | "execution_count": 76, 1824 | "metadata": {}, 1825 | "output_type": "execute_result" 1826 | } 1827 | ], 1828 | "source": [ 1829 | "sorted(simpsons, reverse=True)" 1830 | ] 1831 | }, 1832 | { 1833 | "cell_type": "code", 1834 | "execution_count": 77, 1835 | "metadata": { 1836 | "collapsed": false 1837 | }, 1838 | "outputs": [ 1839 | { 1840 | "data": { 1841 | "text/plain": [ 1842 | "['lisa', 'itchy', 'krusty', 'scratchy']" 1843 | ] 1844 | }, 1845 | "execution_count": 77, 1846 | "metadata": {}, 1847 | "output_type": "execute_result" 1848 | } 1849 | ], 1850 | "source": [ 1851 | "sorted(simpsons, key=len)" 1852 | ] 1853 | }, 1854 | { 1855 | "cell_type": "markdown", 1856 | "metadata": {}, 1857 | "source": [ 1858 | "**Insert into an already sorted list, and keep it sorted:**" 1859 | ] 1860 | }, 1861 | { 1862 | "cell_type": "code", 1863 | "execution_count": 78, 1864 | "metadata": { 1865 | "collapsed": false 1866 | }, 1867 | "outputs": [ 1868 | { 1869 | "data": { 1870 | "text/plain": [ 1871 | "[10, 20, 30, 40, 50]" 1872 | ] 1873 | }, 1874 | "execution_count": 78, 1875 | "metadata": {}, 1876 | "output_type": "execute_result" 1877 | } 1878 | ], 1879 | "source": [ 1880 | "num = [10, 20, 40, 50]\n", 1881 | "from bisect import insort\n", 1882 | "insort(num, 30)\n", 1883 | "num" 1884 | ] 1885 | }, 1886 | { 1887 | "cell_type": "markdown", 1888 | "metadata": {}, 1889 | "source": [ 1890 | "**Object references and copies:**" 1891 | ] 1892 | }, 1893 | { 1894 | "cell_type": "code", 1895 | "execution_count": 79, 1896 | "metadata": { 1897 | "collapsed": true 1898 | }, 1899 | "outputs": [], 1900 | "source": [ 1901 | "# create a second reference to the same list\n", 1902 | "same_num = num" 1903 | ] 1904 | }, 1905 | { 1906 | "cell_type": "code", 1907 | "execution_count": 80, 1908 | "metadata": { 1909 | "collapsed": false 1910 | }, 1911 | "outputs": [ 1912 | { 1913 | "name": "stdout", 1914 | "output_type": "stream", 1915 | "text": [ 1916 | "[0, 20, 30, 40, 50]\n", 1917 | "[0, 20, 30, 40, 50]\n" 1918 | ] 1919 | } 1920 | ], 1921 | "source": [ 1922 | "# modifies both 'num' and 'same_num'\n", 1923 | "same_num[0] = 0\n", 1924 | "print(num)\n", 1925 | "print(same_num)" 1926 | ] 1927 | }, 1928 | { 1929 | "cell_type": "code", 1930 | "execution_count": 81, 1931 | "metadata": { 1932 | "collapsed": true 1933 | }, 1934 | "outputs": [], 1935 | "source": [ 1936 | "# copy a list (two ways)\n", 1937 | "new_num = num[:]\n", 1938 | "new_num = list(num)" 1939 | ] 1940 | }, 1941 | { 1942 | "cell_type": "markdown", 1943 | "metadata": {}, 1944 | "source": [ 1945 | "**Examine objects:**" 1946 | ] 1947 | }, 1948 | { 1949 | "cell_type": "code", 1950 | "execution_count": 82, 1951 | "metadata": { 1952 | "collapsed": false 1953 | }, 1954 | "outputs": [ 1955 | { 1956 | "data": { 1957 | "text/plain": [ 1958 | "True" 1959 | ] 1960 | }, 1961 | "execution_count": 82, 1962 | "metadata": {}, 1963 | "output_type": "execute_result" 1964 | } 1965 | ], 1966 | "source": [ 1967 | "num is same_num # checks whether they are the same object" 1968 | ] 1969 | }, 1970 | { 1971 | "cell_type": "code", 1972 | "execution_count": 83, 1973 | "metadata": { 1974 | "collapsed": false 1975 | }, 1976 | "outputs": [ 1977 | { 1978 | "data": { 1979 | "text/plain": [ 1980 | "False" 1981 | ] 1982 | }, 1983 | "execution_count": 83, 1984 | "metadata": {}, 1985 | "output_type": "execute_result" 1986 | } 1987 | ], 1988 | "source": [ 1989 | "num is new_num" 1990 | ] 1991 | }, 1992 | { 1993 | "cell_type": "code", 1994 | "execution_count": 84, 1995 | "metadata": { 1996 | "collapsed": false 1997 | }, 1998 | "outputs": [ 1999 | { 2000 | "data": { 2001 | "text/plain": [ 2002 | "True" 2003 | ] 2004 | }, 2005 | "execution_count": 84, 2006 | "metadata": {}, 2007 | "output_type": "execute_result" 2008 | } 2009 | ], 2010 | "source": [ 2011 | "num == same_num # checks whether they have the same contents" 2012 | ] 2013 | }, 2014 | { 2015 | "cell_type": "code", 2016 | "execution_count": 85, 2017 | "metadata": { 2018 | "collapsed": false 2019 | }, 2020 | "outputs": [ 2021 | { 2022 | "data": { 2023 | "text/plain": [ 2024 | "True" 2025 | ] 2026 | }, 2027 | "execution_count": 85, 2028 | "metadata": {}, 2029 | "output_type": "execute_result" 2030 | } 2031 | ], 2032 | "source": [ 2033 | "num == new_num" 2034 | ] 2035 | }, 2036 | { 2037 | "cell_type": "markdown", 2038 | "metadata": {}, 2039 | "source": [ 2040 | "[Back to top]" 2041 | ] 2042 | }, 2043 | { 2044 | "cell_type": "markdown", 2045 | "metadata": {}, 2046 | "source": [ 2047 | "## 7. Tuples\n", 2048 | "\n", 2049 | "- **Tuple properties:** ordered, iterable, immutable, can contain multiple data types\n", 2050 | "- Like lists, but they don't change size" 2051 | ] 2052 | }, 2053 | { 2054 | "cell_type": "code", 2055 | "execution_count": 86, 2056 | "metadata": { 2057 | "collapsed": true 2058 | }, 2059 | "outputs": [], 2060 | "source": [ 2061 | "# create a tuple directly\n", 2062 | "digits = (0, 1, 'two')" 2063 | ] 2064 | }, 2065 | { 2066 | "cell_type": "code", 2067 | "execution_count": 87, 2068 | "metadata": { 2069 | "collapsed": true 2070 | }, 2071 | "outputs": [], 2072 | "source": [ 2073 | "# create a tuple from a list\n", 2074 | "digits = tuple([0, 1, 'two'])" 2075 | ] 2076 | }, 2077 | { 2078 | "cell_type": "code", 2079 | "execution_count": 88, 2080 | "metadata": { 2081 | "collapsed": true 2082 | }, 2083 | "outputs": [], 2084 | "source": [ 2085 | "# trailing comma is required to indicate it's a tuple\n", 2086 | "zero = (0,)" 2087 | ] 2088 | }, 2089 | { 2090 | "cell_type": "markdown", 2091 | "metadata": {}, 2092 | "source": [ 2093 | "**Examine a tuple:**" 2094 | ] 2095 | }, 2096 | { 2097 | "cell_type": "code", 2098 | "execution_count": 89, 2099 | "metadata": { 2100 | "collapsed": false 2101 | }, 2102 | "outputs": [ 2103 | { 2104 | "data": { 2105 | "text/plain": [ 2106 | "'two'" 2107 | ] 2108 | }, 2109 | "execution_count": 89, 2110 | "metadata": {}, 2111 | "output_type": "execute_result" 2112 | } 2113 | ], 2114 | "source": [ 2115 | "digits[2]" 2116 | ] 2117 | }, 2118 | { 2119 | "cell_type": "code", 2120 | "execution_count": 90, 2121 | "metadata": { 2122 | "collapsed": false 2123 | }, 2124 | "outputs": [ 2125 | { 2126 | "data": { 2127 | "text/plain": [ 2128 | "3" 2129 | ] 2130 | }, 2131 | "execution_count": 90, 2132 | "metadata": {}, 2133 | "output_type": "execute_result" 2134 | } 2135 | ], 2136 | "source": [ 2137 | "len(digits)" 2138 | ] 2139 | }, 2140 | { 2141 | "cell_type": "code", 2142 | "execution_count": 91, 2143 | "metadata": { 2144 | "collapsed": false 2145 | }, 2146 | "outputs": [ 2147 | { 2148 | "data": { 2149 | "text/plain": [ 2150 | "1" 2151 | ] 2152 | }, 2153 | "execution_count": 91, 2154 | "metadata": {}, 2155 | "output_type": "execute_result" 2156 | } 2157 | ], 2158 | "source": [ 2159 | "# counts the number of instances of that value\n", 2160 | "digits.count(0)" 2161 | ] 2162 | }, 2163 | { 2164 | "cell_type": "code", 2165 | "execution_count": 92, 2166 | "metadata": { 2167 | "collapsed": false 2168 | }, 2169 | "outputs": [ 2170 | { 2171 | "data": { 2172 | "text/plain": [ 2173 | "1" 2174 | ] 2175 | }, 2176 | "execution_count": 92, 2177 | "metadata": {}, 2178 | "output_type": "execute_result" 2179 | } 2180 | ], 2181 | "source": [ 2182 | "# returns the index of the first instance of that value\n", 2183 | "digits.index(1)" 2184 | ] 2185 | }, 2186 | { 2187 | "cell_type": "markdown", 2188 | "metadata": {}, 2189 | "source": [ 2190 | "**Modify a tuple:**" 2191 | ] 2192 | }, 2193 | { 2194 | "cell_type": "code", 2195 | "execution_count": 93, 2196 | "metadata": { 2197 | "collapsed": true 2198 | }, 2199 | "outputs": [], 2200 | "source": [ 2201 | "# elements of a tuple cannot be modified (this would throw an error)\n", 2202 | "# digits[2] = 2" 2203 | ] 2204 | }, 2205 | { 2206 | "cell_type": "code", 2207 | "execution_count": 94, 2208 | "metadata": { 2209 | "collapsed": false 2210 | }, 2211 | "outputs": [ 2212 | { 2213 | "data": { 2214 | "text/plain": [ 2215 | "(0, 1, 'two', 3, 4)" 2216 | ] 2217 | }, 2218 | "execution_count": 94, 2219 | "metadata": {}, 2220 | "output_type": "execute_result" 2221 | } 2222 | ], 2223 | "source": [ 2224 | "# concatenate tuples\n", 2225 | "digits = digits + (3, 4)\n", 2226 | "digits" 2227 | ] 2228 | }, 2229 | { 2230 | "cell_type": "markdown", 2231 | "metadata": {}, 2232 | "source": [ 2233 | "**Other tuple operations:**" 2234 | ] 2235 | }, 2236 | { 2237 | "cell_type": "code", 2238 | "execution_count": 95, 2239 | "metadata": { 2240 | "collapsed": false 2241 | }, 2242 | "outputs": [ 2243 | { 2244 | "data": { 2245 | "text/plain": [ 2246 | "(3, 4, 3, 4)" 2247 | ] 2248 | }, 2249 | "execution_count": 95, 2250 | "metadata": {}, 2251 | "output_type": "execute_result" 2252 | } 2253 | ], 2254 | "source": [ 2255 | "# create a single tuple with elements repeated (also works with lists)\n", 2256 | "(3, 4) * 2" 2257 | ] 2258 | }, 2259 | { 2260 | "cell_type": "code", 2261 | "execution_count": 96, 2262 | "metadata": { 2263 | "collapsed": false 2264 | }, 2265 | "outputs": [ 2266 | { 2267 | "data": { 2268 | "text/plain": [ 2269 | "[(10, 40), (20, 30), (20, 60)]" 2270 | ] 2271 | }, 2272 | "execution_count": 96, 2273 | "metadata": {}, 2274 | "output_type": "execute_result" 2275 | } 2276 | ], 2277 | "source": [ 2278 | "# sort a list of tuples\n", 2279 | "tens = [(20, 60), (10, 40), (20, 30)]\n", 2280 | "sorted(tens) # sorts by first element in tuple, then second element" 2281 | ] 2282 | }, 2283 | { 2284 | "cell_type": "code", 2285 | "execution_count": 97, 2286 | "metadata": { 2287 | "collapsed": false 2288 | }, 2289 | "outputs": [ 2290 | { 2291 | "name": "stdout", 2292 | "output_type": "stream", 2293 | "text": [ 2294 | "male\n", 2295 | "10\n", 2296 | "simpson\n" 2297 | ] 2298 | } 2299 | ], 2300 | "source": [ 2301 | "# tuple unpacking\n", 2302 | "bart = ('male', 10, 'simpson') # create a tuple\n", 2303 | "(sex, age, surname) = bart # assign three values at once\n", 2304 | "print(sex)\n", 2305 | "print(age)\n", 2306 | "print(surname)" 2307 | ] 2308 | }, 2309 | { 2310 | "cell_type": "markdown", 2311 | "metadata": {}, 2312 | "source": [ 2313 | "[Back to top]" 2314 | ] 2315 | }, 2316 | { 2317 | "cell_type": "markdown", 2318 | "metadata": {}, 2319 | "source": [ 2320 | "## 8. Strings\n", 2321 | "\n", 2322 | "- **String properties:** iterable, immutable" 2323 | ] 2324 | }, 2325 | { 2326 | "cell_type": "code", 2327 | "execution_count": 98, 2328 | "metadata": { 2329 | "collapsed": false 2330 | }, 2331 | "outputs": [ 2332 | { 2333 | "data": { 2334 | "text/plain": [ 2335 | "'42'" 2336 | ] 2337 | }, 2338 | "execution_count": 98, 2339 | "metadata": {}, 2340 | "output_type": "execute_result" 2341 | } 2342 | ], 2343 | "source": [ 2344 | "# convert another data type into a string\n", 2345 | "s = str(42)\n", 2346 | "s" 2347 | ] 2348 | }, 2349 | { 2350 | "cell_type": "code", 2351 | "execution_count": 99, 2352 | "metadata": { 2353 | "collapsed": false 2354 | }, 2355 | "outputs": [], 2356 | "source": [ 2357 | "# create a string directly\n", 2358 | "s = 'I like you'" 2359 | ] 2360 | }, 2361 | { 2362 | "cell_type": "markdown", 2363 | "metadata": {}, 2364 | "source": [ 2365 | "**Examine a string:**" 2366 | ] 2367 | }, 2368 | { 2369 | "cell_type": "code", 2370 | "execution_count": 100, 2371 | "metadata": { 2372 | "collapsed": false 2373 | }, 2374 | "outputs": [ 2375 | { 2376 | "data": { 2377 | "text/plain": [ 2378 | "'I'" 2379 | ] 2380 | }, 2381 | "execution_count": 100, 2382 | "metadata": {}, 2383 | "output_type": "execute_result" 2384 | } 2385 | ], 2386 | "source": [ 2387 | "s[0]" 2388 | ] 2389 | }, 2390 | { 2391 | "cell_type": "code", 2392 | "execution_count": 101, 2393 | "metadata": { 2394 | "collapsed": false 2395 | }, 2396 | "outputs": [ 2397 | { 2398 | "data": { 2399 | "text/plain": [ 2400 | "10" 2401 | ] 2402 | }, 2403 | "execution_count": 101, 2404 | "metadata": {}, 2405 | "output_type": "execute_result" 2406 | } 2407 | ], 2408 | "source": [ 2409 | "len(s)" 2410 | ] 2411 | }, 2412 | { 2413 | "cell_type": "markdown", 2414 | "metadata": {}, 2415 | "source": [ 2416 | "**String slicing is like list slicing:**" 2417 | ] 2418 | }, 2419 | { 2420 | "cell_type": "code", 2421 | "execution_count": 102, 2422 | "metadata": { 2423 | "collapsed": false 2424 | }, 2425 | "outputs": [ 2426 | { 2427 | "data": { 2428 | "text/plain": [ 2429 | "'I like'" 2430 | ] 2431 | }, 2432 | "execution_count": 102, 2433 | "metadata": {}, 2434 | "output_type": "execute_result" 2435 | } 2436 | ], 2437 | "source": [ 2438 | "s[:6]" 2439 | ] 2440 | }, 2441 | { 2442 | "cell_type": "code", 2443 | "execution_count": 103, 2444 | "metadata": { 2445 | "collapsed": false 2446 | }, 2447 | "outputs": [ 2448 | { 2449 | "data": { 2450 | "text/plain": [ 2451 | "'you'" 2452 | ] 2453 | }, 2454 | "execution_count": 103, 2455 | "metadata": {}, 2456 | "output_type": "execute_result" 2457 | } 2458 | ], 2459 | "source": [ 2460 | "s[7:]" 2461 | ] 2462 | }, 2463 | { 2464 | "cell_type": "code", 2465 | "execution_count": 104, 2466 | "metadata": { 2467 | "collapsed": false 2468 | }, 2469 | "outputs": [ 2470 | { 2471 | "data": { 2472 | "text/plain": [ 2473 | "'u'" 2474 | ] 2475 | }, 2476 | "execution_count": 104, 2477 | "metadata": {}, 2478 | "output_type": "execute_result" 2479 | } 2480 | ], 2481 | "source": [ 2482 | "s[-1]" 2483 | ] 2484 | }, 2485 | { 2486 | "cell_type": "markdown", 2487 | "metadata": {}, 2488 | "source": [ 2489 | "**Basic string methods (does not modify the original string):**" 2490 | ] 2491 | }, 2492 | { 2493 | "cell_type": "code", 2494 | "execution_count": 105, 2495 | "metadata": { 2496 | "collapsed": false 2497 | }, 2498 | "outputs": [ 2499 | { 2500 | "data": { 2501 | "text/plain": [ 2502 | "'i like you'" 2503 | ] 2504 | }, 2505 | "execution_count": 105, 2506 | "metadata": {}, 2507 | "output_type": "execute_result" 2508 | } 2509 | ], 2510 | "source": [ 2511 | "s.lower()" 2512 | ] 2513 | }, 2514 | { 2515 | "cell_type": "code", 2516 | "execution_count": 106, 2517 | "metadata": { 2518 | "collapsed": false 2519 | }, 2520 | "outputs": [ 2521 | { 2522 | "data": { 2523 | "text/plain": [ 2524 | "'I LIKE YOU'" 2525 | ] 2526 | }, 2527 | "execution_count": 106, 2528 | "metadata": {}, 2529 | "output_type": "execute_result" 2530 | } 2531 | ], 2532 | "source": [ 2533 | "s.upper()" 2534 | ] 2535 | }, 2536 | { 2537 | "cell_type": "code", 2538 | "execution_count": 107, 2539 | "metadata": { 2540 | "collapsed": false 2541 | }, 2542 | "outputs": [ 2543 | { 2544 | "data": { 2545 | "text/plain": [ 2546 | "True" 2547 | ] 2548 | }, 2549 | "execution_count": 107, 2550 | "metadata": {}, 2551 | "output_type": "execute_result" 2552 | } 2553 | ], 2554 | "source": [ 2555 | "s.startswith('I')" 2556 | ] 2557 | }, 2558 | { 2559 | "cell_type": "code", 2560 | "execution_count": 108, 2561 | "metadata": { 2562 | "collapsed": false 2563 | }, 2564 | "outputs": [ 2565 | { 2566 | "data": { 2567 | "text/plain": [ 2568 | "True" 2569 | ] 2570 | }, 2571 | "execution_count": 108, 2572 | "metadata": {}, 2573 | "output_type": "execute_result" 2574 | } 2575 | ], 2576 | "source": [ 2577 | "s.endswith('you')" 2578 | ] 2579 | }, 2580 | { 2581 | "cell_type": "code", 2582 | "execution_count": 109, 2583 | "metadata": { 2584 | "collapsed": false 2585 | }, 2586 | "outputs": [ 2587 | { 2588 | "data": { 2589 | "text/plain": [ 2590 | "False" 2591 | ] 2592 | }, 2593 | "execution_count": 109, 2594 | "metadata": {}, 2595 | "output_type": "execute_result" 2596 | } 2597 | ], 2598 | "source": [ 2599 | "# checks whether every character in the string is a digit\n", 2600 | "s.isdigit()" 2601 | ] 2602 | }, 2603 | { 2604 | "cell_type": "code", 2605 | "execution_count": 110, 2606 | "metadata": { 2607 | "collapsed": false 2608 | }, 2609 | "outputs": [ 2610 | { 2611 | "data": { 2612 | "text/plain": [ 2613 | "2" 2614 | ] 2615 | }, 2616 | "execution_count": 110, 2617 | "metadata": {}, 2618 | "output_type": "execute_result" 2619 | } 2620 | ], 2621 | "source": [ 2622 | "# returns index of first occurrence, but doesn't support regex\n", 2623 | "s.find('like')" 2624 | ] 2625 | }, 2626 | { 2627 | "cell_type": "code", 2628 | "execution_count": 111, 2629 | "metadata": { 2630 | "collapsed": false 2631 | }, 2632 | "outputs": [ 2633 | { 2634 | "data": { 2635 | "text/plain": [ 2636 | "-1" 2637 | ] 2638 | }, 2639 | "execution_count": 111, 2640 | "metadata": {}, 2641 | "output_type": "execute_result" 2642 | } 2643 | ], 2644 | "source": [ 2645 | "# returns -1 since not found\n", 2646 | "s.find('hate')" 2647 | ] 2648 | }, 2649 | { 2650 | "cell_type": "code", 2651 | "execution_count": 112, 2652 | "metadata": { 2653 | "collapsed": false 2654 | }, 2655 | "outputs": [ 2656 | { 2657 | "data": { 2658 | "text/plain": [ 2659 | "'I love you'" 2660 | ] 2661 | }, 2662 | "execution_count": 112, 2663 | "metadata": {}, 2664 | "output_type": "execute_result" 2665 | } 2666 | ], 2667 | "source": [ 2668 | "# replaces all instances of 'like' with 'love'\n", 2669 | "s.replace('like', 'love')" 2670 | ] 2671 | }, 2672 | { 2673 | "cell_type": "markdown", 2674 | "metadata": {}, 2675 | "source": [ 2676 | "**Split a string:**" 2677 | ] 2678 | }, 2679 | { 2680 | "cell_type": "code", 2681 | "execution_count": 113, 2682 | "metadata": { 2683 | "collapsed": false 2684 | }, 2685 | "outputs": [ 2686 | { 2687 | "data": { 2688 | "text/plain": [ 2689 | "['I', 'like', 'you']" 2690 | ] 2691 | }, 2692 | "execution_count": 113, 2693 | "metadata": {}, 2694 | "output_type": "execute_result" 2695 | } 2696 | ], 2697 | "source": [ 2698 | "# split a string into a list of substrings separated by a delimiter\n", 2699 | "s.split(' ')" 2700 | ] 2701 | }, 2702 | { 2703 | "cell_type": "code", 2704 | "execution_count": 114, 2705 | "metadata": { 2706 | "collapsed": false 2707 | }, 2708 | "outputs": [ 2709 | { 2710 | "data": { 2711 | "text/plain": [ 2712 | "['I', 'like', 'you']" 2713 | ] 2714 | }, 2715 | "execution_count": 114, 2716 | "metadata": {}, 2717 | "output_type": "execute_result" 2718 | } 2719 | ], 2720 | "source": [ 2721 | "# equivalent (since space is the default delimiter)\n", 2722 | "s.split()" 2723 | ] 2724 | }, 2725 | { 2726 | "cell_type": "code", 2727 | "execution_count": 115, 2728 | "metadata": { 2729 | "collapsed": false 2730 | }, 2731 | "outputs": [ 2732 | { 2733 | "data": { 2734 | "text/plain": [ 2735 | "['a', ' an', ' the']" 2736 | ] 2737 | }, 2738 | "execution_count": 115, 2739 | "metadata": {}, 2740 | "output_type": "execute_result" 2741 | } 2742 | ], 2743 | "source": [ 2744 | "s2 = 'a, an, the'\n", 2745 | "s2.split(',')" 2746 | ] 2747 | }, 2748 | { 2749 | "cell_type": "markdown", 2750 | "metadata": {}, 2751 | "source": [ 2752 | "**Join or concatenate strings:**" 2753 | ] 2754 | }, 2755 | { 2756 | "cell_type": "code", 2757 | "execution_count": 116, 2758 | "metadata": { 2759 | "collapsed": false 2760 | }, 2761 | "outputs": [ 2762 | { 2763 | "data": { 2764 | "text/plain": [ 2765 | "'larry curly moe'" 2766 | ] 2767 | }, 2768 | "execution_count": 116, 2769 | "metadata": {}, 2770 | "output_type": "execute_result" 2771 | } 2772 | ], 2773 | "source": [ 2774 | "# join a list of strings into one string using a delimiter\n", 2775 | "stooges = ['larry', 'curly', 'moe']\n", 2776 | "' '.join(stooges)" 2777 | ] 2778 | }, 2779 | { 2780 | "cell_type": "code", 2781 | "execution_count": 117, 2782 | "metadata": { 2783 | "collapsed": false, 2784 | "scrolled": true 2785 | }, 2786 | "outputs": [ 2787 | { 2788 | "data": { 2789 | "text/plain": [ 2790 | "'The meaning of life is 42'" 2791 | ] 2792 | }, 2793 | "execution_count": 117, 2794 | "metadata": {}, 2795 | "output_type": "execute_result" 2796 | } 2797 | ], 2798 | "source": [ 2799 | "# concatenate strings\n", 2800 | "s3 = 'The meaning of life is'\n", 2801 | "s4 = '42'\n", 2802 | "s3 + ' ' + s4" 2803 | ] 2804 | }, 2805 | { 2806 | "cell_type": "markdown", 2807 | "metadata": {}, 2808 | "source": [ 2809 | "**Remove whitespace from the start and end of a string:**" 2810 | ] 2811 | }, 2812 | { 2813 | "cell_type": "code", 2814 | "execution_count": 118, 2815 | "metadata": { 2816 | "collapsed": false 2817 | }, 2818 | "outputs": [ 2819 | { 2820 | "data": { 2821 | "text/plain": [ 2822 | "'ham and cheese'" 2823 | ] 2824 | }, 2825 | "execution_count": 118, 2826 | "metadata": {}, 2827 | "output_type": "execute_result" 2828 | } 2829 | ], 2830 | "source": [ 2831 | "s5 = ' ham and cheese '\n", 2832 | "s5.strip()" 2833 | ] 2834 | }, 2835 | { 2836 | "cell_type": "markdown", 2837 | "metadata": {}, 2838 | "source": [ 2839 | "**String substitutions:**" 2840 | ] 2841 | }, 2842 | { 2843 | "cell_type": "code", 2844 | "execution_count": 119, 2845 | "metadata": { 2846 | "collapsed": false 2847 | }, 2848 | "outputs": [ 2849 | { 2850 | "data": { 2851 | "text/plain": [ 2852 | "'raining cats and dogs'" 2853 | ] 2854 | }, 2855 | "execution_count": 119, 2856 | "metadata": {}, 2857 | "output_type": "execute_result" 2858 | } 2859 | ], 2860 | "source": [ 2861 | "# old way\n", 2862 | "'raining %s and %s' % ('cats', 'dogs')" 2863 | ] 2864 | }, 2865 | { 2866 | "cell_type": "code", 2867 | "execution_count": 120, 2868 | "metadata": { 2869 | "collapsed": false 2870 | }, 2871 | "outputs": [ 2872 | { 2873 | "data": { 2874 | "text/plain": [ 2875 | "'raining cats and dogs'" 2876 | ] 2877 | }, 2878 | "execution_count": 120, 2879 | "metadata": {}, 2880 | "output_type": "execute_result" 2881 | } 2882 | ], 2883 | "source": [ 2884 | "# new way\n", 2885 | "'raining {} and {}'.format('cats', 'dogs')" 2886 | ] 2887 | }, 2888 | { 2889 | "cell_type": "code", 2890 | "execution_count": 121, 2891 | "metadata": { 2892 | "collapsed": false, 2893 | "scrolled": true 2894 | }, 2895 | "outputs": [ 2896 | { 2897 | "data": { 2898 | "text/plain": [ 2899 | "'raining cats and dogs'" 2900 | ] 2901 | }, 2902 | "execution_count": 121, 2903 | "metadata": {}, 2904 | "output_type": "execute_result" 2905 | } 2906 | ], 2907 | "source": [ 2908 | "# new way (using named arguments)\n", 2909 | "'raining {arg1} and {arg2}'.format(arg1='cats', arg2='dogs')" 2910 | ] 2911 | }, 2912 | { 2913 | "cell_type": "markdown", 2914 | "metadata": {}, 2915 | "source": [ 2916 | "**String formatting ([more examples](https://mkaz.tech/python-string-format.html)):**" 2917 | ] 2918 | }, 2919 | { 2920 | "cell_type": "code", 2921 | "execution_count": 122, 2922 | "metadata": { 2923 | "collapsed": false 2924 | }, 2925 | "outputs": [ 2926 | { 2927 | "data": { 2928 | "text/plain": [ 2929 | "'pi is 3.14'" 2930 | ] 2931 | }, 2932 | "execution_count": 122, 2933 | "metadata": {}, 2934 | "output_type": "execute_result" 2935 | } 2936 | ], 2937 | "source": [ 2938 | "# use 2 decimal places\n", 2939 | "'pi is {:.2f}'.format(3.14159)" 2940 | ] 2941 | }, 2942 | { 2943 | "cell_type": "markdown", 2944 | "metadata": {}, 2945 | "source": [ 2946 | "**Normal strings versus raw strings:**" 2947 | ] 2948 | }, 2949 | { 2950 | "cell_type": "code", 2951 | "execution_count": 123, 2952 | "metadata": { 2953 | "collapsed": false 2954 | }, 2955 | "outputs": [ 2956 | { 2957 | "name": "stdout", 2958 | "output_type": "stream", 2959 | "text": [ 2960 | "first line\n", 2961 | "second line\n" 2962 | ] 2963 | } 2964 | ], 2965 | "source": [ 2966 | "# normal strings allow for escaped characters\n", 2967 | "print('first line\\nsecond line')" 2968 | ] 2969 | }, 2970 | { 2971 | "cell_type": "code", 2972 | "execution_count": 124, 2973 | "metadata": { 2974 | "collapsed": false 2975 | }, 2976 | "outputs": [ 2977 | { 2978 | "name": "stdout", 2979 | "output_type": "stream", 2980 | "text": [ 2981 | "first line\\nfirst line\n" 2982 | ] 2983 | } 2984 | ], 2985 | "source": [ 2986 | "# raw strings treat backslashes as literal characters\n", 2987 | "print(r'first line\\nfirst line')" 2988 | ] 2989 | }, 2990 | { 2991 | "cell_type": "markdown", 2992 | "metadata": {}, 2993 | "source": [ 2994 | "[Back to top]" 2995 | ] 2996 | }, 2997 | { 2998 | "cell_type": "markdown", 2999 | "metadata": {}, 3000 | "source": [ 3001 | "## 9. Dictionaries\n", 3002 | "\n", 3003 | "- **Dictionary properties:** unordered, iterable, mutable, can contain multiple data types\n", 3004 | "- Made of key-value pairs\n", 3005 | "- Keys must be unique, and can be strings, numbers, or tuples\n", 3006 | "- Values can be any type" 3007 | ] 3008 | }, 3009 | { 3010 | "cell_type": "code", 3011 | "execution_count": 125, 3012 | "metadata": { 3013 | "collapsed": true 3014 | }, 3015 | "outputs": [], 3016 | "source": [ 3017 | "# create an empty dictionary (two ways)\n", 3018 | "empty_dict = {}\n", 3019 | "empty_dict = dict()" 3020 | ] 3021 | }, 3022 | { 3023 | "cell_type": "code", 3024 | "execution_count": 126, 3025 | "metadata": { 3026 | "collapsed": false 3027 | }, 3028 | "outputs": [ 3029 | { 3030 | "data": { 3031 | "text/plain": [ 3032 | "{'dad': 'homer', 'mom': 'marge', 'size': 6}" 3033 | ] 3034 | }, 3035 | "execution_count": 126, 3036 | "metadata": {}, 3037 | "output_type": "execute_result" 3038 | } 3039 | ], 3040 | "source": [ 3041 | "# create a dictionary (two ways)\n", 3042 | "family = {'dad':'homer', 'mom':'marge', 'size':6}\n", 3043 | "family = dict(dad='homer', mom='marge', size=6)\n", 3044 | "family" 3045 | ] 3046 | }, 3047 | { 3048 | "cell_type": "code", 3049 | "execution_count": 127, 3050 | "metadata": { 3051 | "collapsed": false 3052 | }, 3053 | "outputs": [ 3054 | { 3055 | "data": { 3056 | "text/plain": [ 3057 | "{'dad': 'homer', 'mom': 'marge', 'size': 6}" 3058 | ] 3059 | }, 3060 | "execution_count": 127, 3061 | "metadata": {}, 3062 | "output_type": "execute_result" 3063 | } 3064 | ], 3065 | "source": [ 3066 | "# convert a list of tuples into a dictionary\n", 3067 | "list_of_tuples = [('dad', 'homer'), ('mom', 'marge'), ('size', 6)]\n", 3068 | "family = dict(list_of_tuples)\n", 3069 | "family" 3070 | ] 3071 | }, 3072 | { 3073 | "cell_type": "markdown", 3074 | "metadata": {}, 3075 | "source": [ 3076 | "**Examine a dictionary:**" 3077 | ] 3078 | }, 3079 | { 3080 | "cell_type": "code", 3081 | "execution_count": 128, 3082 | "metadata": { 3083 | "collapsed": false 3084 | }, 3085 | "outputs": [ 3086 | { 3087 | "data": { 3088 | "text/plain": [ 3089 | "'homer'" 3090 | ] 3091 | }, 3092 | "execution_count": 128, 3093 | "metadata": {}, 3094 | "output_type": "execute_result" 3095 | } 3096 | ], 3097 | "source": [ 3098 | "# pass a key to return its value\n", 3099 | "family['dad']" 3100 | ] 3101 | }, 3102 | { 3103 | "cell_type": "code", 3104 | "execution_count": 129, 3105 | "metadata": { 3106 | "collapsed": false 3107 | }, 3108 | "outputs": [ 3109 | { 3110 | "data": { 3111 | "text/plain": [ 3112 | "3" 3113 | ] 3114 | }, 3115 | "execution_count": 129, 3116 | "metadata": {}, 3117 | "output_type": "execute_result" 3118 | } 3119 | ], 3120 | "source": [ 3121 | "# return the number of key-value pairs\n", 3122 | "len(family)" 3123 | ] 3124 | }, 3125 | { 3126 | "cell_type": "code", 3127 | "execution_count": 130, 3128 | "metadata": { 3129 | "collapsed": false 3130 | }, 3131 | "outputs": [ 3132 | { 3133 | "data": { 3134 | "text/plain": [ 3135 | "True" 3136 | ] 3137 | }, 3138 | "execution_count": 130, 3139 | "metadata": {}, 3140 | "output_type": "execute_result" 3141 | } 3142 | ], 3143 | "source": [ 3144 | "# check if key exists in dictionary\n", 3145 | "'mom' in family" 3146 | ] 3147 | }, 3148 | { 3149 | "cell_type": "code", 3150 | "execution_count": 131, 3151 | "metadata": { 3152 | "collapsed": false 3153 | }, 3154 | "outputs": [ 3155 | { 3156 | "data": { 3157 | "text/plain": [ 3158 | "False" 3159 | ] 3160 | }, 3161 | "execution_count": 131, 3162 | "metadata": {}, 3163 | "output_type": "execute_result" 3164 | } 3165 | ], 3166 | "source": [ 3167 | "# dictionary values are not checked\n", 3168 | "'marge' in family" 3169 | ] 3170 | }, 3171 | { 3172 | "cell_type": "code", 3173 | "execution_count": 132, 3174 | "metadata": { 3175 | "collapsed": false 3176 | }, 3177 | "outputs": [ 3178 | { 3179 | "data": { 3180 | "text/plain": [ 3181 | "['dad', 'mom', 'size']" 3182 | ] 3183 | }, 3184 | "execution_count": 132, 3185 | "metadata": {}, 3186 | "output_type": "execute_result" 3187 | } 3188 | ], 3189 | "source": [ 3190 | "# returns a list of keys (Python 2) or an iterable view (Python 3)\n", 3191 | "family.keys()" 3192 | ] 3193 | }, 3194 | { 3195 | "cell_type": "code", 3196 | "execution_count": 133, 3197 | "metadata": { 3198 | "collapsed": false 3199 | }, 3200 | "outputs": [ 3201 | { 3202 | "data": { 3203 | "text/plain": [ 3204 | "['homer', 'marge', 6]" 3205 | ] 3206 | }, 3207 | "execution_count": 133, 3208 | "metadata": {}, 3209 | "output_type": "execute_result" 3210 | } 3211 | ], 3212 | "source": [ 3213 | "# returns a list of values (Python 2) or an iterable view (Python 3)\n", 3214 | "family.values()" 3215 | ] 3216 | }, 3217 | { 3218 | "cell_type": "code", 3219 | "execution_count": 134, 3220 | "metadata": { 3221 | "collapsed": false 3222 | }, 3223 | "outputs": [ 3224 | { 3225 | "data": { 3226 | "text/plain": [ 3227 | "[('dad', 'homer'), ('mom', 'marge'), ('size', 6)]" 3228 | ] 3229 | }, 3230 | "execution_count": 134, 3231 | "metadata": {}, 3232 | "output_type": "execute_result" 3233 | } 3234 | ], 3235 | "source": [ 3236 | "# returns a list of key-value pairs (Python 2) or an iterable view (Python 3)\n", 3237 | "family.items()" 3238 | ] 3239 | }, 3240 | { 3241 | "cell_type": "markdown", 3242 | "metadata": {}, 3243 | "source": [ 3244 | "**Modify a dictionary (does not return the dictionary):**" 3245 | ] 3246 | }, 3247 | { 3248 | "cell_type": "code", 3249 | "execution_count": 135, 3250 | "metadata": { 3251 | "collapsed": false 3252 | }, 3253 | "outputs": [ 3254 | { 3255 | "data": { 3256 | "text/plain": [ 3257 | "{'cat': 'snowball', 'dad': 'homer', 'mom': 'marge', 'size': 6}" 3258 | ] 3259 | }, 3260 | "execution_count": 135, 3261 | "metadata": {}, 3262 | "output_type": "execute_result" 3263 | } 3264 | ], 3265 | "source": [ 3266 | "# add a new entry\n", 3267 | "family['cat'] = 'snowball'\n", 3268 | "family" 3269 | ] 3270 | }, 3271 | { 3272 | "cell_type": "code", 3273 | "execution_count": 136, 3274 | "metadata": { 3275 | "collapsed": false 3276 | }, 3277 | "outputs": [ 3278 | { 3279 | "data": { 3280 | "text/plain": [ 3281 | "{'cat': 'snowball ii', 'dad': 'homer', 'mom': 'marge', 'size': 6}" 3282 | ] 3283 | }, 3284 | "execution_count": 136, 3285 | "metadata": {}, 3286 | "output_type": "execute_result" 3287 | } 3288 | ], 3289 | "source": [ 3290 | "# edit an existing entry\n", 3291 | "family['cat'] = 'snowball ii'\n", 3292 | "family" 3293 | ] 3294 | }, 3295 | { 3296 | "cell_type": "code", 3297 | "execution_count": 137, 3298 | "metadata": { 3299 | "collapsed": false 3300 | }, 3301 | "outputs": [ 3302 | { 3303 | "data": { 3304 | "text/plain": [ 3305 | "{'dad': 'homer', 'mom': 'marge', 'size': 6}" 3306 | ] 3307 | }, 3308 | "execution_count": 137, 3309 | "metadata": {}, 3310 | "output_type": "execute_result" 3311 | } 3312 | ], 3313 | "source": [ 3314 | "# delete an entry\n", 3315 | "del family['cat']\n", 3316 | "family" 3317 | ] 3318 | }, 3319 | { 3320 | "cell_type": "code", 3321 | "execution_count": 138, 3322 | "metadata": { 3323 | "collapsed": false 3324 | }, 3325 | "outputs": [ 3326 | { 3327 | "data": { 3328 | "text/plain": [ 3329 | "{'dad': 'homer', 'kids': ['bart', 'lisa'], 'mom': 'marge', 'size': 6}" 3330 | ] 3331 | }, 3332 | "execution_count": 138, 3333 | "metadata": {}, 3334 | "output_type": "execute_result" 3335 | } 3336 | ], 3337 | "source": [ 3338 | "# dictionary value can be a list\n", 3339 | "family['kids'] = ['bart', 'lisa']\n", 3340 | "family" 3341 | ] 3342 | }, 3343 | { 3344 | "cell_type": "code", 3345 | "execution_count": 139, 3346 | "metadata": { 3347 | "collapsed": false 3348 | }, 3349 | "outputs": [ 3350 | { 3351 | "data": { 3352 | "text/plain": [ 3353 | "'homer'" 3354 | ] 3355 | }, 3356 | "execution_count": 139, 3357 | "metadata": {}, 3358 | "output_type": "execute_result" 3359 | } 3360 | ], 3361 | "source": [ 3362 | "# remove an entry and return the value\n", 3363 | "family.pop('dad')" 3364 | ] 3365 | }, 3366 | { 3367 | "cell_type": "code", 3368 | "execution_count": 140, 3369 | "metadata": { 3370 | "collapsed": false 3371 | }, 3372 | "outputs": [ 3373 | { 3374 | "data": { 3375 | "text/plain": [ 3376 | "{'baby': 'maggie',\n", 3377 | " 'grandpa': 'abe',\n", 3378 | " 'kids': ['bart', 'lisa'],\n", 3379 | " 'mom': 'marge',\n", 3380 | " 'size': 6}" 3381 | ] 3382 | }, 3383 | "execution_count": 140, 3384 | "metadata": {}, 3385 | "output_type": "execute_result" 3386 | } 3387 | ], 3388 | "source": [ 3389 | "# add multiple entries\n", 3390 | "family.update({'baby':'maggie', 'grandpa':'abe'})\n", 3391 | "family" 3392 | ] 3393 | }, 3394 | { 3395 | "cell_type": "markdown", 3396 | "metadata": {}, 3397 | "source": [ 3398 | "**Access values more safely with `get`:**" 3399 | ] 3400 | }, 3401 | { 3402 | "cell_type": "code", 3403 | "execution_count": 141, 3404 | "metadata": { 3405 | "collapsed": false 3406 | }, 3407 | "outputs": [ 3408 | { 3409 | "data": { 3410 | "text/plain": [ 3411 | "'marge'" 3412 | ] 3413 | }, 3414 | "execution_count": 141, 3415 | "metadata": {}, 3416 | "output_type": "execute_result" 3417 | } 3418 | ], 3419 | "source": [ 3420 | "family['mom']" 3421 | ] 3422 | }, 3423 | { 3424 | "cell_type": "code", 3425 | "execution_count": 142, 3426 | "metadata": { 3427 | "collapsed": false 3428 | }, 3429 | "outputs": [ 3430 | { 3431 | "data": { 3432 | "text/plain": [ 3433 | "'marge'" 3434 | ] 3435 | }, 3436 | "execution_count": 142, 3437 | "metadata": {}, 3438 | "output_type": "execute_result" 3439 | } 3440 | ], 3441 | "source": [ 3442 | "# equivalent to a dictionary lookup\n", 3443 | "family.get('mom')" 3444 | ] 3445 | }, 3446 | { 3447 | "cell_type": "code", 3448 | "execution_count": 143, 3449 | "metadata": { 3450 | "collapsed": false 3451 | }, 3452 | "outputs": [], 3453 | "source": [ 3454 | "# this would throw an error since the key does not exist\n", 3455 | "# family['grandma']" 3456 | ] 3457 | }, 3458 | { 3459 | "cell_type": "code", 3460 | "execution_count": 144, 3461 | "metadata": { 3462 | "collapsed": true 3463 | }, 3464 | "outputs": [], 3465 | "source": [ 3466 | "# return None if not found\n", 3467 | "family.get('grandma')" 3468 | ] 3469 | }, 3470 | { 3471 | "cell_type": "code", 3472 | "execution_count": 145, 3473 | "metadata": { 3474 | "collapsed": false 3475 | }, 3476 | "outputs": [ 3477 | { 3478 | "data": { 3479 | "text/plain": [ 3480 | "'not found'" 3481 | ] 3482 | }, 3483 | "execution_count": 145, 3484 | "metadata": {}, 3485 | "output_type": "execute_result" 3486 | } 3487 | ], 3488 | "source": [ 3489 | "# provide a default return value if not found\n", 3490 | "family.get('grandma', 'not found')" 3491 | ] 3492 | }, 3493 | { 3494 | "cell_type": "markdown", 3495 | "metadata": {}, 3496 | "source": [ 3497 | "**Access a list element within a dictionary:**" 3498 | ] 3499 | }, 3500 | { 3501 | "cell_type": "code", 3502 | "execution_count": 146, 3503 | "metadata": { 3504 | "collapsed": false 3505 | }, 3506 | "outputs": [ 3507 | { 3508 | "data": { 3509 | "text/plain": [ 3510 | "'bart'" 3511 | ] 3512 | }, 3513 | "execution_count": 146, 3514 | "metadata": {}, 3515 | "output_type": "execute_result" 3516 | } 3517 | ], 3518 | "source": [ 3519 | "family['kids'][0]" 3520 | ] 3521 | }, 3522 | { 3523 | "cell_type": "code", 3524 | "execution_count": 147, 3525 | "metadata": { 3526 | "collapsed": false 3527 | }, 3528 | "outputs": [ 3529 | { 3530 | "data": { 3531 | "text/plain": [ 3532 | "{'baby': 'maggie',\n", 3533 | " 'grandpa': 'abe',\n", 3534 | " 'kids': ['bart'],\n", 3535 | " 'mom': 'marge',\n", 3536 | " 'size': 6}" 3537 | ] 3538 | }, 3539 | "execution_count": 147, 3540 | "metadata": {}, 3541 | "output_type": "execute_result" 3542 | } 3543 | ], 3544 | "source": [ 3545 | "family['kids'].remove('lisa')\n", 3546 | "family" 3547 | ] 3548 | }, 3549 | { 3550 | "cell_type": "markdown", 3551 | "metadata": {}, 3552 | "source": [ 3553 | "**String substitution using a dictionary:**" 3554 | ] 3555 | }, 3556 | { 3557 | "cell_type": "code", 3558 | "execution_count": 148, 3559 | "metadata": { 3560 | "collapsed": false 3561 | }, 3562 | "outputs": [ 3563 | { 3564 | "data": { 3565 | "text/plain": [ 3566 | "'youngest child is maggie'" 3567 | ] 3568 | }, 3569 | "execution_count": 148, 3570 | "metadata": {}, 3571 | "output_type": "execute_result" 3572 | } 3573 | ], 3574 | "source": [ 3575 | "'youngest child is %(baby)s' % family" 3576 | ] 3577 | }, 3578 | { 3579 | "cell_type": "markdown", 3580 | "metadata": {}, 3581 | "source": [ 3582 | "[Back to top]" 3583 | ] 3584 | }, 3585 | { 3586 | "cell_type": "markdown", 3587 | "metadata": {}, 3588 | "source": [ 3589 | "## 10. Sets\n", 3590 | "\n", 3591 | "- **Set properties:** unordered, iterable, mutable, can contain multiple data types\n", 3592 | "- Made of unique elements (strings, numbers, or tuples)\n", 3593 | "- Like dictionaries, but with keys only (no values)" 3594 | ] 3595 | }, 3596 | { 3597 | "cell_type": "code", 3598 | "execution_count": 149, 3599 | "metadata": { 3600 | "collapsed": true 3601 | }, 3602 | "outputs": [], 3603 | "source": [ 3604 | "# create an empty set\n", 3605 | "empty_set = set()" 3606 | ] 3607 | }, 3608 | { 3609 | "cell_type": "code", 3610 | "execution_count": 150, 3611 | "metadata": { 3612 | "collapsed": true 3613 | }, 3614 | "outputs": [], 3615 | "source": [ 3616 | "# create a set directly\n", 3617 | "languages = {'python', 'r', 'java'}" 3618 | ] 3619 | }, 3620 | { 3621 | "cell_type": "code", 3622 | "execution_count": 151, 3623 | "metadata": { 3624 | "collapsed": true 3625 | }, 3626 | "outputs": [], 3627 | "source": [ 3628 | "# create a set from a list\n", 3629 | "snakes = set(['cobra', 'viper', 'python'])" 3630 | ] 3631 | }, 3632 | { 3633 | "cell_type": "markdown", 3634 | "metadata": {}, 3635 | "source": [ 3636 | "**Examine a set:**" 3637 | ] 3638 | }, 3639 | { 3640 | "cell_type": "code", 3641 | "execution_count": 152, 3642 | "metadata": { 3643 | "collapsed": false 3644 | }, 3645 | "outputs": [ 3646 | { 3647 | "data": { 3648 | "text/plain": [ 3649 | "3" 3650 | ] 3651 | }, 3652 | "execution_count": 152, 3653 | "metadata": {}, 3654 | "output_type": "execute_result" 3655 | } 3656 | ], 3657 | "source": [ 3658 | "len(languages)" 3659 | ] 3660 | }, 3661 | { 3662 | "cell_type": "code", 3663 | "execution_count": 153, 3664 | "metadata": { 3665 | "collapsed": false 3666 | }, 3667 | "outputs": [ 3668 | { 3669 | "data": { 3670 | "text/plain": [ 3671 | "True" 3672 | ] 3673 | }, 3674 | "execution_count": 153, 3675 | "metadata": {}, 3676 | "output_type": "execute_result" 3677 | } 3678 | ], 3679 | "source": [ 3680 | "'python' in languages" 3681 | ] 3682 | }, 3683 | { 3684 | "cell_type": "markdown", 3685 | "metadata": {}, 3686 | "source": [ 3687 | "**Set operations:**" 3688 | ] 3689 | }, 3690 | { 3691 | "cell_type": "code", 3692 | "execution_count": 154, 3693 | "metadata": { 3694 | "collapsed": false 3695 | }, 3696 | "outputs": [ 3697 | { 3698 | "data": { 3699 | "text/plain": [ 3700 | "{'python'}" 3701 | ] 3702 | }, 3703 | "execution_count": 154, 3704 | "metadata": {}, 3705 | "output_type": "execute_result" 3706 | } 3707 | ], 3708 | "source": [ 3709 | "# intersection\n", 3710 | "languages & snakes" 3711 | ] 3712 | }, 3713 | { 3714 | "cell_type": "code", 3715 | "execution_count": 155, 3716 | "metadata": { 3717 | "collapsed": false 3718 | }, 3719 | "outputs": [ 3720 | { 3721 | "data": { 3722 | "text/plain": [ 3723 | "{'cobra', 'java', 'python', 'r', 'viper'}" 3724 | ] 3725 | }, 3726 | "execution_count": 155, 3727 | "metadata": {}, 3728 | "output_type": "execute_result" 3729 | } 3730 | ], 3731 | "source": [ 3732 | "# union\n", 3733 | "languages | snakes" 3734 | ] 3735 | }, 3736 | { 3737 | "cell_type": "code", 3738 | "execution_count": 156, 3739 | "metadata": { 3740 | "collapsed": false 3741 | }, 3742 | "outputs": [ 3743 | { 3744 | "data": { 3745 | "text/plain": [ 3746 | "{'java', 'r'}" 3747 | ] 3748 | }, 3749 | "execution_count": 156, 3750 | "metadata": {}, 3751 | "output_type": "execute_result" 3752 | } 3753 | ], 3754 | "source": [ 3755 | "# set difference\n", 3756 | "languages - snakes" 3757 | ] 3758 | }, 3759 | { 3760 | "cell_type": "code", 3761 | "execution_count": 157, 3762 | "metadata": { 3763 | "collapsed": false 3764 | }, 3765 | "outputs": [ 3766 | { 3767 | "data": { 3768 | "text/plain": [ 3769 | "{'cobra', 'viper'}" 3770 | ] 3771 | }, 3772 | "execution_count": 157, 3773 | "metadata": {}, 3774 | "output_type": "execute_result" 3775 | } 3776 | ], 3777 | "source": [ 3778 | "# set difference\n", 3779 | "snakes - languages" 3780 | ] 3781 | }, 3782 | { 3783 | "cell_type": "markdown", 3784 | "metadata": {}, 3785 | "source": [ 3786 | "**Modify a set (does not return the set):**" 3787 | ] 3788 | }, 3789 | { 3790 | "cell_type": "code", 3791 | "execution_count": 158, 3792 | "metadata": { 3793 | "collapsed": false 3794 | }, 3795 | "outputs": [ 3796 | { 3797 | "data": { 3798 | "text/plain": [ 3799 | "{'java', 'python', 'r', 'sql'}" 3800 | ] 3801 | }, 3802 | "execution_count": 158, 3803 | "metadata": {}, 3804 | "output_type": "execute_result" 3805 | } 3806 | ], 3807 | "source": [ 3808 | "# add a new element\n", 3809 | "languages.add('sql')\n", 3810 | "languages" 3811 | ] 3812 | }, 3813 | { 3814 | "cell_type": "code", 3815 | "execution_count": 159, 3816 | "metadata": { 3817 | "collapsed": false 3818 | }, 3819 | "outputs": [ 3820 | { 3821 | "data": { 3822 | "text/plain": [ 3823 | "{'java', 'python', 'r', 'sql'}" 3824 | ] 3825 | }, 3826 | "execution_count": 159, 3827 | "metadata": {}, 3828 | "output_type": "execute_result" 3829 | } 3830 | ], 3831 | "source": [ 3832 | "# try to add an existing element (ignored, no error)\n", 3833 | "languages.add('r')\n", 3834 | "languages" 3835 | ] 3836 | }, 3837 | { 3838 | "cell_type": "code", 3839 | "execution_count": 160, 3840 | "metadata": { 3841 | "collapsed": false 3842 | }, 3843 | "outputs": [ 3844 | { 3845 | "data": { 3846 | "text/plain": [ 3847 | "{'python', 'r', 'sql'}" 3848 | ] 3849 | }, 3850 | "execution_count": 160, 3851 | "metadata": {}, 3852 | "output_type": "execute_result" 3853 | } 3854 | ], 3855 | "source": [ 3856 | "# remove an element\n", 3857 | "languages.remove('java')\n", 3858 | "languages" 3859 | ] 3860 | }, 3861 | { 3862 | "cell_type": "code", 3863 | "execution_count": 161, 3864 | "metadata": { 3865 | "collapsed": false 3866 | }, 3867 | "outputs": [], 3868 | "source": [ 3869 | "# try to remove a non-existing element (this would throw an error)\n", 3870 | "# languages.remove('c')" 3871 | ] 3872 | }, 3873 | { 3874 | "cell_type": "code", 3875 | "execution_count": 162, 3876 | "metadata": { 3877 | "collapsed": false 3878 | }, 3879 | "outputs": [ 3880 | { 3881 | "data": { 3882 | "text/plain": [ 3883 | "{'python', 'r', 'sql'}" 3884 | ] 3885 | }, 3886 | "execution_count": 162, 3887 | "metadata": {}, 3888 | "output_type": "execute_result" 3889 | } 3890 | ], 3891 | "source": [ 3892 | "# remove an element if present, but ignored otherwise\n", 3893 | "languages.discard('c')\n", 3894 | "languages" 3895 | ] 3896 | }, 3897 | { 3898 | "cell_type": "code", 3899 | "execution_count": 163, 3900 | "metadata": { 3901 | "collapsed": false 3902 | }, 3903 | "outputs": [ 3904 | { 3905 | "data": { 3906 | "text/plain": [ 3907 | "'python'" 3908 | ] 3909 | }, 3910 | "execution_count": 163, 3911 | "metadata": {}, 3912 | "output_type": "execute_result" 3913 | } 3914 | ], 3915 | "source": [ 3916 | "# remove and return an arbitrary element\n", 3917 | "languages.pop()" 3918 | ] 3919 | }, 3920 | { 3921 | "cell_type": "code", 3922 | "execution_count": 164, 3923 | "metadata": { 3924 | "collapsed": false 3925 | }, 3926 | "outputs": [ 3927 | { 3928 | "data": { 3929 | "text/plain": [ 3930 | "set()" 3931 | ] 3932 | }, 3933 | "execution_count": 164, 3934 | "metadata": {}, 3935 | "output_type": "execute_result" 3936 | } 3937 | ], 3938 | "source": [ 3939 | "# remove all elements\n", 3940 | "languages.clear()\n", 3941 | "languages" 3942 | ] 3943 | }, 3944 | { 3945 | "cell_type": "code", 3946 | "execution_count": 165, 3947 | "metadata": { 3948 | "collapsed": false 3949 | }, 3950 | "outputs": [ 3951 | { 3952 | "data": { 3953 | "text/plain": [ 3954 | "{'go', 'spark'}" 3955 | ] 3956 | }, 3957 | "execution_count": 165, 3958 | "metadata": {}, 3959 | "output_type": "execute_result" 3960 | } 3961 | ], 3962 | "source": [ 3963 | "# add multiple elements (can also pass a set)\n", 3964 | "languages.update(['go', 'spark'])\n", 3965 | "languages" 3966 | ] 3967 | }, 3968 | { 3969 | "cell_type": "markdown", 3970 | "metadata": {}, 3971 | "source": [ 3972 | "**Get a sorted list of unique elements from a list:**" 3973 | ] 3974 | }, 3975 | { 3976 | "cell_type": "code", 3977 | "execution_count": 166, 3978 | "metadata": { 3979 | "collapsed": false 3980 | }, 3981 | "outputs": [ 3982 | { 3983 | "data": { 3984 | "text/plain": [ 3985 | "[0, 1, 2, 9]" 3986 | ] 3987 | }, 3988 | "execution_count": 166, 3989 | "metadata": {}, 3990 | "output_type": "execute_result" 3991 | } 3992 | ], 3993 | "source": [ 3994 | "sorted(set([9, 0, 2, 1, 0]))" 3995 | ] 3996 | }, 3997 | { 3998 | "cell_type": "markdown", 3999 | "metadata": {}, 4000 | "source": [ 4001 | "[Back to top]" 4002 | ] 4003 | }, 4004 | { 4005 | "cell_type": "markdown", 4006 | "metadata": {}, 4007 | "source": [ 4008 | "## 11. Defining Functions" 4009 | ] 4010 | }, 4011 | { 4012 | "cell_type": "markdown", 4013 | "metadata": {}, 4014 | "source": [ 4015 | "**Define a function with no arguments and no return values:**" 4016 | ] 4017 | }, 4018 | { 4019 | "cell_type": "code", 4020 | "execution_count": 167, 4021 | "metadata": { 4022 | "collapsed": true 4023 | }, 4024 | "outputs": [], 4025 | "source": [ 4026 | "def print_text():\n", 4027 | " print('this is text')" 4028 | ] 4029 | }, 4030 | { 4031 | "cell_type": "code", 4032 | "execution_count": 168, 4033 | "metadata": { 4034 | "collapsed": false 4035 | }, 4036 | "outputs": [ 4037 | { 4038 | "name": "stdout", 4039 | "output_type": "stream", 4040 | "text": [ 4041 | "this is text\n" 4042 | ] 4043 | } 4044 | ], 4045 | "source": [ 4046 | "# call the function\n", 4047 | "print_text()" 4048 | ] 4049 | }, 4050 | { 4051 | "cell_type": "markdown", 4052 | "metadata": {}, 4053 | "source": [ 4054 | "**Define a function with one argument and no return values:**" 4055 | ] 4056 | }, 4057 | { 4058 | "cell_type": "code", 4059 | "execution_count": 169, 4060 | "metadata": { 4061 | "collapsed": true 4062 | }, 4063 | "outputs": [], 4064 | "source": [ 4065 | "def print_this(x):\n", 4066 | " print(x)" 4067 | ] 4068 | }, 4069 | { 4070 | "cell_type": "code", 4071 | "execution_count": 170, 4072 | "metadata": { 4073 | "collapsed": false 4074 | }, 4075 | "outputs": [ 4076 | { 4077 | "name": "stdout", 4078 | "output_type": "stream", 4079 | "text": [ 4080 | "3\n" 4081 | ] 4082 | } 4083 | ], 4084 | "source": [ 4085 | "# call the function\n", 4086 | "print_this(3)" 4087 | ] 4088 | }, 4089 | { 4090 | "cell_type": "code", 4091 | "execution_count": 171, 4092 | "metadata": { 4093 | "collapsed": false 4094 | }, 4095 | "outputs": [ 4096 | { 4097 | "name": "stdout", 4098 | "output_type": "stream", 4099 | "text": [ 4100 | "3\n" 4101 | ] 4102 | } 4103 | ], 4104 | "source": [ 4105 | "# prints 3, but doesn't assign 3 to n because the function has no return statement\n", 4106 | "n = print_this(3)" 4107 | ] 4108 | }, 4109 | { 4110 | "cell_type": "markdown", 4111 | "metadata": {}, 4112 | "source": [ 4113 | "**Define a function with one argument and one return value:**" 4114 | ] 4115 | }, 4116 | { 4117 | "cell_type": "code", 4118 | "execution_count": 172, 4119 | "metadata": { 4120 | "collapsed": true 4121 | }, 4122 | "outputs": [], 4123 | "source": [ 4124 | "def square_this(x):\n", 4125 | " return x**2" 4126 | ] 4127 | }, 4128 | { 4129 | "cell_type": "code", 4130 | "execution_count": 173, 4131 | "metadata": { 4132 | "collapsed": true 4133 | }, 4134 | "outputs": [], 4135 | "source": [ 4136 | "# include an optional docstring to describe the effect of a function\n", 4137 | "def square_this(x):\n", 4138 | " \"\"\"Return the square of a number.\"\"\"\n", 4139 | " return x**2" 4140 | ] 4141 | }, 4142 | { 4143 | "cell_type": "code", 4144 | "execution_count": 174, 4145 | "metadata": { 4146 | "collapsed": false 4147 | }, 4148 | "outputs": [ 4149 | { 4150 | "data": { 4151 | "text/plain": [ 4152 | "9" 4153 | ] 4154 | }, 4155 | "execution_count": 174, 4156 | "metadata": {}, 4157 | "output_type": "execute_result" 4158 | } 4159 | ], 4160 | "source": [ 4161 | "# call the function\n", 4162 | "square_this(3)" 4163 | ] 4164 | }, 4165 | { 4166 | "cell_type": "code", 4167 | "execution_count": 175, 4168 | "metadata": { 4169 | "collapsed": true 4170 | }, 4171 | "outputs": [], 4172 | "source": [ 4173 | "# assigns 9 to var, but does not print 9\n", 4174 | "var = square_this(3)" 4175 | ] 4176 | }, 4177 | { 4178 | "cell_type": "markdown", 4179 | "metadata": {}, 4180 | "source": [ 4181 | "**Define a function with two 'positional arguments' (no default values) and one 'keyword argument' (has a default value):**\n" 4182 | ] 4183 | }, 4184 | { 4185 | "cell_type": "code", 4186 | "execution_count": 176, 4187 | "metadata": { 4188 | "collapsed": true 4189 | }, 4190 | "outputs": [], 4191 | "source": [ 4192 | "def calc(a, b, op='add'):\n", 4193 | " if op == 'add':\n", 4194 | " return a + b\n", 4195 | " elif op == 'sub':\n", 4196 | " return a - b\n", 4197 | " else:\n", 4198 | " print('valid operations are add and sub')" 4199 | ] 4200 | }, 4201 | { 4202 | "cell_type": "code", 4203 | "execution_count": 177, 4204 | "metadata": { 4205 | "collapsed": false 4206 | }, 4207 | "outputs": [ 4208 | { 4209 | "data": { 4210 | "text/plain": [ 4211 | "14" 4212 | ] 4213 | }, 4214 | "execution_count": 177, 4215 | "metadata": {}, 4216 | "output_type": "execute_result" 4217 | } 4218 | ], 4219 | "source": [ 4220 | "# call the function\n", 4221 | "calc(10, 4, op='add')" 4222 | ] 4223 | }, 4224 | { 4225 | "cell_type": "code", 4226 | "execution_count": 178, 4227 | "metadata": { 4228 | "collapsed": false 4229 | }, 4230 | "outputs": [ 4231 | { 4232 | "data": { 4233 | "text/plain": [ 4234 | "14" 4235 | ] 4236 | }, 4237 | "execution_count": 178, 4238 | "metadata": {}, 4239 | "output_type": "execute_result" 4240 | } 4241 | ], 4242 | "source": [ 4243 | "# unnamed arguments are inferred by position\n", 4244 | "calc(10, 4, 'add')" 4245 | ] 4246 | }, 4247 | { 4248 | "cell_type": "code", 4249 | "execution_count": 179, 4250 | "metadata": { 4251 | "collapsed": false 4252 | }, 4253 | "outputs": [ 4254 | { 4255 | "data": { 4256 | "text/plain": [ 4257 | "14" 4258 | ] 4259 | }, 4260 | "execution_count": 179, 4261 | "metadata": {}, 4262 | "output_type": "execute_result" 4263 | } 4264 | ], 4265 | "source": [ 4266 | "# default for 'op' is 'add'\n", 4267 | "calc(10, 4)" 4268 | ] 4269 | }, 4270 | { 4271 | "cell_type": "code", 4272 | "execution_count": 180, 4273 | "metadata": { 4274 | "collapsed": false 4275 | }, 4276 | "outputs": [ 4277 | { 4278 | "data": { 4279 | "text/plain": [ 4280 | "6" 4281 | ] 4282 | }, 4283 | "execution_count": 180, 4284 | "metadata": {}, 4285 | "output_type": "execute_result" 4286 | } 4287 | ], 4288 | "source": [ 4289 | "calc(10, 4, 'sub')" 4290 | ] 4291 | }, 4292 | { 4293 | "cell_type": "code", 4294 | "execution_count": 181, 4295 | "metadata": { 4296 | "collapsed": false 4297 | }, 4298 | "outputs": [ 4299 | { 4300 | "name": "stdout", 4301 | "output_type": "stream", 4302 | "text": [ 4303 | "valid operations are add and sub\n" 4304 | ] 4305 | } 4306 | ], 4307 | "source": [ 4308 | "calc(10, 4, 'div')" 4309 | ] 4310 | }, 4311 | { 4312 | "cell_type": "markdown", 4313 | "metadata": {}, 4314 | "source": [ 4315 | "**Use `pass` as a placeholder if you haven't written the function body:**" 4316 | ] 4317 | }, 4318 | { 4319 | "cell_type": "code", 4320 | "execution_count": 182, 4321 | "metadata": { 4322 | "collapsed": true 4323 | }, 4324 | "outputs": [], 4325 | "source": [ 4326 | "def stub():\n", 4327 | " pass" 4328 | ] 4329 | }, 4330 | { 4331 | "cell_type": "markdown", 4332 | "metadata": {}, 4333 | "source": [ 4334 | "**Return two values from a single function:**" 4335 | ] 4336 | }, 4337 | { 4338 | "cell_type": "code", 4339 | "execution_count": 183, 4340 | "metadata": { 4341 | "collapsed": true 4342 | }, 4343 | "outputs": [], 4344 | "source": [ 4345 | "def min_max(nums):\n", 4346 | " return min(nums), max(nums)" 4347 | ] 4348 | }, 4349 | { 4350 | "cell_type": "code", 4351 | "execution_count": 184, 4352 | "metadata": { 4353 | "collapsed": false 4354 | }, 4355 | "outputs": [ 4356 | { 4357 | "data": { 4358 | "text/plain": [ 4359 | "(1, 3)" 4360 | ] 4361 | }, 4362 | "execution_count": 184, 4363 | "metadata": {}, 4364 | "output_type": "execute_result" 4365 | } 4366 | ], 4367 | "source": [ 4368 | "# return values can be assigned to a single variable as a tuple\n", 4369 | "nums = [1, 2, 3]\n", 4370 | "min_max_num = min_max(nums)\n", 4371 | "min_max_num" 4372 | ] 4373 | }, 4374 | { 4375 | "cell_type": "code", 4376 | "execution_count": 185, 4377 | "metadata": { 4378 | "collapsed": false 4379 | }, 4380 | "outputs": [ 4381 | { 4382 | "name": "stdout", 4383 | "output_type": "stream", 4384 | "text": [ 4385 | "1\n", 4386 | "3\n" 4387 | ] 4388 | } 4389 | ], 4390 | "source": [ 4391 | "# return values can be assigned into multiple variables using tuple unpacking\n", 4392 | "min_num, max_num = min_max(nums)\n", 4393 | "print(min_num)\n", 4394 | "print(max_num)" 4395 | ] 4396 | }, 4397 | { 4398 | "cell_type": "markdown", 4399 | "metadata": {}, 4400 | "source": [ 4401 | "[Back to top]" 4402 | ] 4403 | }, 4404 | { 4405 | "cell_type": "markdown", 4406 | "metadata": {}, 4407 | "source": [ 4408 | "## 12. Anonymous (Lambda) Functions\n", 4409 | "\n", 4410 | "- Primarily used to temporarily define a function for use by another function" 4411 | ] 4412 | }, 4413 | { 4414 | "cell_type": "code", 4415 | "execution_count": 186, 4416 | "metadata": { 4417 | "collapsed": true 4418 | }, 4419 | "outputs": [], 4420 | "source": [ 4421 | "# define a function the \"usual\" way\n", 4422 | "def squared(x):\n", 4423 | " return x**2" 4424 | ] 4425 | }, 4426 | { 4427 | "cell_type": "code", 4428 | "execution_count": 187, 4429 | "metadata": { 4430 | "collapsed": true 4431 | }, 4432 | "outputs": [], 4433 | "source": [ 4434 | "# define an identical function using lambda\n", 4435 | "squared = lambda x: x**2" 4436 | ] 4437 | }, 4438 | { 4439 | "cell_type": "markdown", 4440 | "metadata": {}, 4441 | "source": [ 4442 | "**Sort a list of strings by the last letter:**" 4443 | ] 4444 | }, 4445 | { 4446 | "cell_type": "code", 4447 | "execution_count": 188, 4448 | "metadata": { 4449 | "collapsed": false 4450 | }, 4451 | "outputs": [ 4452 | { 4453 | "data": { 4454 | "text/plain": [ 4455 | "['marge', 'homer', 'bart']" 4456 | ] 4457 | }, 4458 | "execution_count": 188, 4459 | "metadata": {}, 4460 | "output_type": "execute_result" 4461 | } 4462 | ], 4463 | "source": [ 4464 | "# without using lambda\n", 4465 | "simpsons = ['homer', 'marge', 'bart']\n", 4466 | "def last_letter(word):\n", 4467 | " return word[-1]\n", 4468 | "sorted(simpsons, key=last_letter)" 4469 | ] 4470 | }, 4471 | { 4472 | "cell_type": "code", 4473 | "execution_count": 189, 4474 | "metadata": { 4475 | "collapsed": false 4476 | }, 4477 | "outputs": [ 4478 | { 4479 | "data": { 4480 | "text/plain": [ 4481 | "['marge', 'homer', 'bart']" 4482 | ] 4483 | }, 4484 | "execution_count": 189, 4485 | "metadata": {}, 4486 | "output_type": "execute_result" 4487 | } 4488 | ], 4489 | "source": [ 4490 | "# using lambda\n", 4491 | "sorted(simpsons, key=lambda word: word[-1])" 4492 | ] 4493 | }, 4494 | { 4495 | "cell_type": "markdown", 4496 | "metadata": {}, 4497 | "source": [ 4498 | "[Back to top]" 4499 | ] 4500 | }, 4501 | { 4502 | "cell_type": "markdown", 4503 | "metadata": {}, 4504 | "source": [ 4505 | "## 13. For Loops and While Loops" 4506 | ] 4507 | }, 4508 | { 4509 | "cell_type": "markdown", 4510 | "metadata": {}, 4511 | "source": [ 4512 | "**`range` returns a list of integers (Python 2) or a sequence (Python 3):**" 4513 | ] 4514 | }, 4515 | { 4516 | "cell_type": "code", 4517 | "execution_count": 190, 4518 | "metadata": { 4519 | "collapsed": false 4520 | }, 4521 | "outputs": [ 4522 | { 4523 | "data": { 4524 | "text/plain": [ 4525 | "[0, 1, 2]" 4526 | ] 4527 | }, 4528 | "execution_count": 190, 4529 | "metadata": {}, 4530 | "output_type": "execute_result" 4531 | } 4532 | ], 4533 | "source": [ 4534 | "# includes the start value but excludes the stop value\n", 4535 | "range(0, 3)" 4536 | ] 4537 | }, 4538 | { 4539 | "cell_type": "code", 4540 | "execution_count": 191, 4541 | "metadata": { 4542 | "collapsed": false 4543 | }, 4544 | "outputs": [ 4545 | { 4546 | "data": { 4547 | "text/plain": [ 4548 | "[0, 1, 2]" 4549 | ] 4550 | }, 4551 | "execution_count": 191, 4552 | "metadata": {}, 4553 | "output_type": "execute_result" 4554 | } 4555 | ], 4556 | "source": [ 4557 | "# default start value is 0\n", 4558 | "range(3)" 4559 | ] 4560 | }, 4561 | { 4562 | "cell_type": "code", 4563 | "execution_count": 192, 4564 | "metadata": { 4565 | "collapsed": false 4566 | }, 4567 | "outputs": [ 4568 | { 4569 | "data": { 4570 | "text/plain": [ 4571 | "[0, 2, 4]" 4572 | ] 4573 | }, 4574 | "execution_count": 192, 4575 | "metadata": {}, 4576 | "output_type": "execute_result" 4577 | } 4578 | ], 4579 | "source": [ 4580 | "# third argument is the step value\n", 4581 | "range(0, 5, 2)" 4582 | ] 4583 | }, 4584 | { 4585 | "cell_type": "code", 4586 | "execution_count": 193, 4587 | "metadata": { 4588 | "collapsed": false 4589 | }, 4590 | "outputs": [ 4591 | { 4592 | "data": { 4593 | "text/plain": [ 4594 | "xrange(100, 100000, 5)" 4595 | ] 4596 | }, 4597 | "execution_count": 193, 4598 | "metadata": {}, 4599 | "output_type": "execute_result" 4600 | } 4601 | ], 4602 | "source": [ 4603 | "# Python 2 only: use xrange to create a sequence rather than a list (saves memory)\n", 4604 | "xrange(100, 100000, 5)" 4605 | ] 4606 | }, 4607 | { 4608 | "cell_type": "markdown", 4609 | "metadata": {}, 4610 | "source": [ 4611 | "**`for` loops:**" 4612 | ] 4613 | }, 4614 | { 4615 | "cell_type": "code", 4616 | "execution_count": 194, 4617 | "metadata": { 4618 | "collapsed": false 4619 | }, 4620 | "outputs": [ 4621 | { 4622 | "name": "stdout", 4623 | "output_type": "stream", 4624 | "text": [ 4625 | "APPLE\n", 4626 | "BANANA\n", 4627 | "CHERRY\n" 4628 | ] 4629 | } 4630 | ], 4631 | "source": [ 4632 | "# not the recommended style\n", 4633 | "fruits = ['apple', 'banana', 'cherry']\n", 4634 | "for i in range(len(fruits)):\n", 4635 | " print(fruits[i].upper())" 4636 | ] 4637 | }, 4638 | { 4639 | "cell_type": "code", 4640 | "execution_count": 195, 4641 | "metadata": { 4642 | "collapsed": false 4643 | }, 4644 | "outputs": [ 4645 | { 4646 | "name": "stdout", 4647 | "output_type": "stream", 4648 | "text": [ 4649 | "APPLE\n", 4650 | "BANANA\n", 4651 | "CHERRY\n" 4652 | ] 4653 | } 4654 | ], 4655 | "source": [ 4656 | "# recommended style\n", 4657 | "for fruit in fruits:\n", 4658 | " print(fruit.upper())" 4659 | ] 4660 | }, 4661 | { 4662 | "cell_type": "code", 4663 | "execution_count": 196, 4664 | "metadata": { 4665 | "collapsed": false 4666 | }, 4667 | "outputs": [ 4668 | { 4669 | "name": "stdout", 4670 | "output_type": "stream", 4671 | "text": [ 4672 | "('dad', 'homer')\n", 4673 | "('mom', 'marge')\n", 4674 | "('size', 6)\n" 4675 | ] 4676 | } 4677 | ], 4678 | "source": [ 4679 | "# iterate through two things at once (using tuple unpacking)\n", 4680 | "family = {'dad':'homer', 'mom':'marge', 'size':6}\n", 4681 | "for key, value in family.items():\n", 4682 | " print(key, value)" 4683 | ] 4684 | }, 4685 | { 4686 | "cell_type": "code", 4687 | "execution_count": 197, 4688 | "metadata": { 4689 | "collapsed": false 4690 | }, 4691 | "outputs": [ 4692 | { 4693 | "name": "stdout", 4694 | "output_type": "stream", 4695 | "text": [ 4696 | "(0, 'apple')\n", 4697 | "(1, 'banana')\n", 4698 | "(2, 'cherry')\n" 4699 | ] 4700 | } 4701 | ], 4702 | "source": [ 4703 | "# use enumerate if you need to access the index value within the loop\n", 4704 | "for index, fruit in enumerate(fruits):\n", 4705 | " print(index, fruit)" 4706 | ] 4707 | }, 4708 | { 4709 | "cell_type": "markdown", 4710 | "metadata": {}, 4711 | "source": [ 4712 | "**`for`/`else` loop:**" 4713 | ] 4714 | }, 4715 | { 4716 | "cell_type": "code", 4717 | "execution_count": 198, 4718 | "metadata": { 4719 | "collapsed": false 4720 | }, 4721 | "outputs": [ 4722 | { 4723 | "name": "stdout", 4724 | "output_type": "stream", 4725 | "text": [ 4726 | "Found the banana!\n" 4727 | ] 4728 | } 4729 | ], 4730 | "source": [ 4731 | "for fruit in fruits:\n", 4732 | " if fruit == 'banana':\n", 4733 | " print('Found the banana!')\n", 4734 | " break # exit the loop and skip the 'else' block\n", 4735 | "else:\n", 4736 | " # this block executes ONLY if the for loop completes without hitting 'break'\n", 4737 | " print(\"Can't find the banana\")" 4738 | ] 4739 | }, 4740 | { 4741 | "cell_type": "markdown", 4742 | "metadata": {}, 4743 | "source": [ 4744 | "**`while` loop:**" 4745 | ] 4746 | }, 4747 | { 4748 | "cell_type": "code", 4749 | "execution_count": 199, 4750 | "metadata": { 4751 | "collapsed": false 4752 | }, 4753 | "outputs": [ 4754 | { 4755 | "name": "stdout", 4756 | "output_type": "stream", 4757 | "text": [ 4758 | "This will print 5 times\n", 4759 | "This will print 5 times\n", 4760 | "This will print 5 times\n", 4761 | "This will print 5 times\n", 4762 | "This will print 5 times\n" 4763 | ] 4764 | } 4765 | ], 4766 | "source": [ 4767 | "count = 0\n", 4768 | "while count < 5:\n", 4769 | " print('This will print 5 times')\n", 4770 | " count += 1 # equivalent to 'count = count + 1'" 4771 | ] 4772 | }, 4773 | { 4774 | "cell_type": "markdown", 4775 | "metadata": {}, 4776 | "source": [ 4777 | "[Back to top]" 4778 | ] 4779 | }, 4780 | { 4781 | "cell_type": "markdown", 4782 | "metadata": {}, 4783 | "source": [ 4784 | "## 14. Comprehensions" 4785 | ] 4786 | }, 4787 | { 4788 | "cell_type": "markdown", 4789 | "metadata": {}, 4790 | "source": [ 4791 | "**List comprehension:**" 4792 | ] 4793 | }, 4794 | { 4795 | "cell_type": "code", 4796 | "execution_count": 200, 4797 | "metadata": { 4798 | "collapsed": false 4799 | }, 4800 | "outputs": [ 4801 | { 4802 | "data": { 4803 | "text/plain": [ 4804 | "[1, 8, 27, 64, 125]" 4805 | ] 4806 | }, 4807 | "execution_count": 200, 4808 | "metadata": {}, 4809 | "output_type": "execute_result" 4810 | } 4811 | ], 4812 | "source": [ 4813 | "# for loop to create a list of cubes\n", 4814 | "nums = [1, 2, 3, 4, 5]\n", 4815 | "cubes = []\n", 4816 | "for num in nums:\n", 4817 | " cubes.append(num**3)\n", 4818 | "cubes" 4819 | ] 4820 | }, 4821 | { 4822 | "cell_type": "code", 4823 | "execution_count": 201, 4824 | "metadata": { 4825 | "collapsed": false 4826 | }, 4827 | "outputs": [ 4828 | { 4829 | "data": { 4830 | "text/plain": [ 4831 | "[1, 8, 27, 64, 125]" 4832 | ] 4833 | }, 4834 | "execution_count": 201, 4835 | "metadata": {}, 4836 | "output_type": "execute_result" 4837 | } 4838 | ], 4839 | "source": [ 4840 | "# equivalent list comprehension\n", 4841 | "cubes = [num**3 for num in nums]\n", 4842 | "cubes" 4843 | ] 4844 | }, 4845 | { 4846 | "cell_type": "code", 4847 | "execution_count": 202, 4848 | "metadata": { 4849 | "collapsed": false 4850 | }, 4851 | "outputs": [ 4852 | { 4853 | "data": { 4854 | "text/plain": [ 4855 | "[8, 64]" 4856 | ] 4857 | }, 4858 | "execution_count": 202, 4859 | "metadata": {}, 4860 | "output_type": "execute_result" 4861 | } 4862 | ], 4863 | "source": [ 4864 | "# for loop to create a list of cubes of even numbers\n", 4865 | "cubes_of_even = []\n", 4866 | "for num in nums:\n", 4867 | " if num % 2 == 0:\n", 4868 | " cubes_of_even.append(num**3)\n", 4869 | "cubes_of_even" 4870 | ] 4871 | }, 4872 | { 4873 | "cell_type": "code", 4874 | "execution_count": 203, 4875 | "metadata": { 4876 | "collapsed": false 4877 | }, 4878 | "outputs": [ 4879 | { 4880 | "data": { 4881 | "text/plain": [ 4882 | "[8, 64]" 4883 | ] 4884 | }, 4885 | "execution_count": 203, 4886 | "metadata": {}, 4887 | "output_type": "execute_result" 4888 | } 4889 | ], 4890 | "source": [ 4891 | "# equivalent list comprehension\n", 4892 | "# syntax: [expression for variable in iterable if condition]\n", 4893 | "cubes_of_even = [num**3 for num in nums if num % 2 == 0]\n", 4894 | "cubes_of_even" 4895 | ] 4896 | }, 4897 | { 4898 | "cell_type": "code", 4899 | "execution_count": 204, 4900 | "metadata": { 4901 | "collapsed": false 4902 | }, 4903 | "outputs": [ 4904 | { 4905 | "data": { 4906 | "text/plain": [ 4907 | "[1, 8, 9, 64, 25]" 4908 | ] 4909 | }, 4910 | "execution_count": 204, 4911 | "metadata": {}, 4912 | "output_type": "execute_result" 4913 | } 4914 | ], 4915 | "source": [ 4916 | "# for loop to cube even numbers and square odd numbers\n", 4917 | "cubes_and_squares = []\n", 4918 | "for num in nums:\n", 4919 | " if num % 2 == 0:\n", 4920 | " cubes_and_squares.append(num**3)\n", 4921 | " else:\n", 4922 | " cubes_and_squares.append(num**2)\n", 4923 | "cubes_and_squares" 4924 | ] 4925 | }, 4926 | { 4927 | "cell_type": "code", 4928 | "execution_count": 205, 4929 | "metadata": { 4930 | "collapsed": false 4931 | }, 4932 | "outputs": [ 4933 | { 4934 | "data": { 4935 | "text/plain": [ 4936 | "[1, 8, 9, 64, 25]" 4937 | ] 4938 | }, 4939 | "execution_count": 205, 4940 | "metadata": {}, 4941 | "output_type": "execute_result" 4942 | } 4943 | ], 4944 | "source": [ 4945 | "# equivalent list comprehension (using a ternary expression)\n", 4946 | "# syntax: [true_condition if condition else false_condition for variable in iterable]\n", 4947 | "cubes_and_squares = [num**3 if num % 2 == 0 else num**2 for num in nums]\n", 4948 | "cubes_and_squares" 4949 | ] 4950 | }, 4951 | { 4952 | "cell_type": "code", 4953 | "execution_count": 206, 4954 | "metadata": { 4955 | "collapsed": false 4956 | }, 4957 | "outputs": [ 4958 | { 4959 | "data": { 4960 | "text/plain": [ 4961 | "[1, 2, 3, 4]" 4962 | ] 4963 | }, 4964 | "execution_count": 206, 4965 | "metadata": {}, 4966 | "output_type": "execute_result" 4967 | } 4968 | ], 4969 | "source": [ 4970 | "# for loop to flatten a 2d-matrix\n", 4971 | "matrix = [[1, 2], [3, 4]]\n", 4972 | "items = []\n", 4973 | "for row in matrix:\n", 4974 | " for item in row:\n", 4975 | " items.append(item)\n", 4976 | "items" 4977 | ] 4978 | }, 4979 | { 4980 | "cell_type": "code", 4981 | "execution_count": 207, 4982 | "metadata": { 4983 | "collapsed": false 4984 | }, 4985 | "outputs": [ 4986 | { 4987 | "data": { 4988 | "text/plain": [ 4989 | "[1, 2, 3, 4]" 4990 | ] 4991 | }, 4992 | "execution_count": 207, 4993 | "metadata": {}, 4994 | "output_type": "execute_result" 4995 | } 4996 | ], 4997 | "source": [ 4998 | "# equivalent list comprehension\n", 4999 | "items = [item for row in matrix\n", 5000 | " for item in row]\n", 5001 | "items" 5002 | ] 5003 | }, 5004 | { 5005 | "cell_type": "markdown", 5006 | "metadata": {}, 5007 | "source": [ 5008 | "**Set comprehension:**" 5009 | ] 5010 | }, 5011 | { 5012 | "cell_type": "code", 5013 | "execution_count": 208, 5014 | "metadata": { 5015 | "collapsed": false 5016 | }, 5017 | "outputs": [ 5018 | { 5019 | "data": { 5020 | "text/plain": [ 5021 | "{5, 6}" 5022 | ] 5023 | }, 5024 | "execution_count": 208, 5025 | "metadata": {}, 5026 | "output_type": "execute_result" 5027 | } 5028 | ], 5029 | "source": [ 5030 | "fruits = ['apple', 'banana', 'cherry']\n", 5031 | "unique_lengths = {len(fruit) for fruit in fruits}\n", 5032 | "unique_lengths" 5033 | ] 5034 | }, 5035 | { 5036 | "cell_type": "markdown", 5037 | "metadata": {}, 5038 | "source": [ 5039 | "**Dictionary comprehension:**" 5040 | ] 5041 | }, 5042 | { 5043 | "cell_type": "code", 5044 | "execution_count": 209, 5045 | "metadata": { 5046 | "collapsed": false 5047 | }, 5048 | "outputs": [ 5049 | { 5050 | "data": { 5051 | "text/plain": [ 5052 | "{'apple': 5, 'banana': 6, 'cherry': 6}" 5053 | ] 5054 | }, 5055 | "execution_count": 209, 5056 | "metadata": {}, 5057 | "output_type": "execute_result" 5058 | } 5059 | ], 5060 | "source": [ 5061 | "fruit_lengths = {fruit:len(fruit) for fruit in fruits}\n", 5062 | "fruit_lengths" 5063 | ] 5064 | }, 5065 | { 5066 | "cell_type": "code", 5067 | "execution_count": 210, 5068 | "metadata": { 5069 | "collapsed": false 5070 | }, 5071 | "outputs": [ 5072 | { 5073 | "data": { 5074 | "text/plain": [ 5075 | "{'apple': 0, 'banana': 1, 'cherry': 2}" 5076 | ] 5077 | }, 5078 | "execution_count": 210, 5079 | "metadata": {}, 5080 | "output_type": "execute_result" 5081 | } 5082 | ], 5083 | "source": [ 5084 | "fruit_indices = {fruit:index for index, fruit in enumerate(fruits)}\n", 5085 | "fruit_indices" 5086 | ] 5087 | }, 5088 | { 5089 | "cell_type": "markdown", 5090 | "metadata": {}, 5091 | "source": [ 5092 | "[Back to top]" 5093 | ] 5094 | }, 5095 | { 5096 | "cell_type": "markdown", 5097 | "metadata": {}, 5098 | "source": [ 5099 | "## 15. Map and Filter" 5100 | ] 5101 | }, 5102 | { 5103 | "cell_type": "markdown", 5104 | "metadata": {}, 5105 | "source": [ 5106 | "**`map` applies a function to every element of a sequence and returns a list (Python 2) or iterator (Python 3):**" 5107 | ] 5108 | }, 5109 | { 5110 | "cell_type": "code", 5111 | "execution_count": 211, 5112 | "metadata": { 5113 | "collapsed": false 5114 | }, 5115 | "outputs": [ 5116 | { 5117 | "data": { 5118 | "text/plain": [ 5119 | "[5, 5, 4]" 5120 | ] 5121 | }, 5122 | "execution_count": 211, 5123 | "metadata": {}, 5124 | "output_type": "execute_result" 5125 | } 5126 | ], 5127 | "source": [ 5128 | "simpsons = ['homer', 'marge', 'bart']\n", 5129 | "map(len, simpsons)" 5130 | ] 5131 | }, 5132 | { 5133 | "cell_type": "code", 5134 | "execution_count": 212, 5135 | "metadata": { 5136 | "collapsed": false 5137 | }, 5138 | "outputs": [ 5139 | { 5140 | "data": { 5141 | "text/plain": [ 5142 | "[5, 5, 4]" 5143 | ] 5144 | }, 5145 | "execution_count": 212, 5146 | "metadata": {}, 5147 | "output_type": "execute_result" 5148 | } 5149 | ], 5150 | "source": [ 5151 | "# equivalent list comprehension\n", 5152 | "[len(word) for word in simpsons]" 5153 | ] 5154 | }, 5155 | { 5156 | "cell_type": "code", 5157 | "execution_count": 213, 5158 | "metadata": { 5159 | "collapsed": false 5160 | }, 5161 | "outputs": [ 5162 | { 5163 | "data": { 5164 | "text/plain": [ 5165 | "['r', 'e', 't']" 5166 | ] 5167 | }, 5168 | "execution_count": 213, 5169 | "metadata": {}, 5170 | "output_type": "execute_result" 5171 | } 5172 | ], 5173 | "source": [ 5174 | "map(lambda word: word[-1], simpsons)" 5175 | ] 5176 | }, 5177 | { 5178 | "cell_type": "code", 5179 | "execution_count": 214, 5180 | "metadata": { 5181 | "collapsed": false 5182 | }, 5183 | "outputs": [ 5184 | { 5185 | "data": { 5186 | "text/plain": [ 5187 | "['r', 'e', 't']" 5188 | ] 5189 | }, 5190 | "execution_count": 214, 5191 | "metadata": {}, 5192 | "output_type": "execute_result" 5193 | } 5194 | ], 5195 | "source": [ 5196 | "# equivalent list comprehension\n", 5197 | "[word[-1] for word in simpsons]" 5198 | ] 5199 | }, 5200 | { 5201 | "cell_type": "markdown", 5202 | "metadata": {}, 5203 | "source": [ 5204 | "**`filter` returns a list (Python 2) or iterator (Python 3) containing the elements from a sequence for which a condition is `True`:**" 5205 | ] 5206 | }, 5207 | { 5208 | "cell_type": "code", 5209 | "execution_count": 215, 5210 | "metadata": { 5211 | "collapsed": false 5212 | }, 5213 | "outputs": [ 5214 | { 5215 | "data": { 5216 | "text/plain": [ 5217 | "[0, 2, 4]" 5218 | ] 5219 | }, 5220 | "execution_count": 215, 5221 | "metadata": {}, 5222 | "output_type": "execute_result" 5223 | } 5224 | ], 5225 | "source": [ 5226 | "nums = range(5)\n", 5227 | "filter(lambda x: x % 2 == 0, nums)" 5228 | ] 5229 | }, 5230 | { 5231 | "cell_type": "code", 5232 | "execution_count": 216, 5233 | "metadata": { 5234 | "collapsed": false 5235 | }, 5236 | "outputs": [ 5237 | { 5238 | "data": { 5239 | "text/plain": [ 5240 | "[0, 2, 4]" 5241 | ] 5242 | }, 5243 | "execution_count": 216, 5244 | "metadata": {}, 5245 | "output_type": "execute_result" 5246 | } 5247 | ], 5248 | "source": [ 5249 | "# equivalent list comprehension\n", 5250 | "[num for num in nums if num % 2 == 0]" 5251 | ] 5252 | }, 5253 | { 5254 | "cell_type": "markdown", 5255 | "metadata": {}, 5256 | "source": [ 5257 | "[Back to top]" 5258 | ] 5259 | } 5260 | ], 5261 | "metadata": { 5262 | "kernelspec": { 5263 | "display_name": "Python 2", 5264 | "language": "python", 5265 | "name": "python2" 5266 | }, 5267 | "language_info": { 5268 | "codemirror_mode": { 5269 | "name": "ipython", 5270 | "version": 2 5271 | }, 5272 | "file_extension": ".py", 5273 | "mimetype": "text/x-python", 5274 | "name": "python", 5275 | "nbconvert_exporter": "python", 5276 | "pygments_lexer": "ipython2", 5277 | "version": "2.7.11" 5278 | } 5279 | }, 5280 | "nbformat": 4, 5281 | "nbformat_minor": 0 5282 | } 5283 | -------------------------------------------------------------------------------- /reference.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Python Quick Reference 3 | https://github.com/justmarkham/python-reference 4 | 5 | By Kevin Markham (kevin@dataschool.io) 6 | http://www.dataschool.io 7 | 8 | Table of Contents: 9 | Imports 10 | Data Types 11 | Math 12 | Comparisons and Boolean Operations 13 | Conditional Statements 14 | Lists 15 | Tuples 16 | Strings 17 | Dictionaries 18 | Sets 19 | Defining Functions 20 | Anonymous (Lambda) Functions 21 | For Loops and While Loops 22 | Comprehensions 23 | Map and Filter 24 | ''' 25 | 26 | 27 | 28 | ### IMPORTS ### 29 | 30 | # 'generic import' of math module 31 | import math 32 | math.sqrt(25) 33 | 34 | # import a function 35 | from math import sqrt 36 | sqrt(25) # no longer have to reference the module 37 | 38 | # import multiple functions at once 39 | from math import cos, floor 40 | 41 | # import all functions in a module (generally discouraged) 42 | from csv import * 43 | 44 | # define an alias 45 | import datetime as dt 46 | 47 | # show all functions in math module 48 | dir(math) 49 | 50 | 51 | 52 | ### DATA TYPES ### 53 | 54 | # determine the type of an object 55 | type(2) # returns 'int' 56 | type(2.0) # returns 'float' 57 | type('two') # returns 'str' 58 | type(True) # returns 'bool' 59 | type(None) # returns 'NoneType' 60 | 61 | # check if an object is of a given type 62 | isinstance(2.0, int) # returns False 63 | isinstance(2.0, (int, float)) # returns True 64 | 65 | # convert an object to a given type 66 | float(2) 67 | int(2.9) 68 | str(2.9) 69 | 70 | # zero, None, and empty containers are converted to False 71 | bool(0) 72 | bool(None) 73 | bool('') # empty string 74 | bool([]) # empty list 75 | bool({}) # empty dictionary 76 | 77 | # non-empty containers and non-zeros are converted to True 78 | bool(2) 79 | bool('two') 80 | bool([2]) 81 | 82 | 83 | 84 | ### MATH ### 85 | 86 | # basic operations 87 | 10 + 4 # add (returns 14) 88 | 10 - 4 # subtract (returns 6) 89 | 10 * 4 # multiply (returns 40) 90 | 10 ** 4 # exponent (returns 10000) 91 | 5 % 4 # modulo (returns 1) - computes the remainder 92 | 10 / 4 # divide (returns 2 in Python 2, returns 2.5 in Python 3) 93 | 10 / float(4) # divide (returns 2.5) 94 | 95 | # force '/' in Python 2 to perform 'true division' (unnecessary in Python 3) 96 | from __future__ import division 97 | 10 / 4 # true division (returns 2.5) 98 | 10 // 4 # floor division (returns 2) 99 | 100 | 101 | 102 | ### COMPARISONS AND BOOLEAN OPERATIONS ### 103 | 104 | # assignment statement 105 | x = 5 106 | 107 | # comparisons (these return True) 108 | x > 3 109 | x >= 3 110 | x != 3 111 | x == 5 112 | 113 | # boolean operations (these return True) 114 | 5 > 3 and 6 > 3 115 | 5 > 3 or 5 < 3 116 | not False 117 | False or not False and True # evaluation order: not, and, or 118 | 119 | 120 | 121 | ### CONDITIONAL STATEMENTS ### 122 | 123 | # if statement 124 | if x > 0: 125 | print('positive') 126 | 127 | # if/else statement 128 | if x > 0: 129 | print('positive') 130 | else: 131 | print('zero or negative') 132 | 133 | # if/elif/else statement 134 | if x > 0: 135 | print('positive') 136 | elif x == 0: 137 | print('zero') 138 | else: 139 | print('negative') 140 | 141 | # single-line if statement (sometimes discouraged) 142 | if x > 0: print('positive') 143 | 144 | # single-line if/else statement (sometimes discouraged) 145 | # known as a 'ternary operator' 146 | 'positive' if x > 0 else 'zero or negative' 147 | 148 | 149 | 150 | ### LISTS ### 151 | ## properties: ordered, iterable, mutable, can contain multiple data types 152 | 153 | # create an empty list (two ways) 154 | empty_list = [] 155 | empty_list = list() 156 | 157 | # create a list 158 | simpsons = ['homer', 'marge', 'bart'] 159 | 160 | # examine a list 161 | simpsons[0] # print element 0 ('homer') 162 | len(simpsons) # returns the length (3) 163 | 164 | # modify a list (does not return the list) 165 | simpsons.append('lisa') # append element to end 166 | simpsons.extend(['itchy', 'scratchy']) # append multiple elements to end 167 | simpsons.insert(0, 'maggie') # insert element at index 0 (shifts everything right) 168 | simpsons.remove('bart') # search for first instance and remove it 169 | simpsons.pop(0) # remove element 0 and return it 170 | del simpsons[0] # remove element 0 (does not return it) 171 | simpsons[0] = 'krusty' # replace element 0 172 | 173 | # concatenate lists (slower than 'extend' method) 174 | neighbors = simpsons + ['ned', 'rod', 'todd'] 175 | 176 | # find elements in a list 177 | simpsons.count('lisa') # counts the number of instances 178 | simpsons.index('itchy') # returns index of first instance 179 | 180 | # list slicing [start:end:step] 181 | weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri'] 182 | weekdays[0] # element 0 183 | weekdays[0:3] # elements 0, 1, 2 184 | weekdays[:3] # elements 0, 1, 2 185 | weekdays[3:] # elements 3, 4 186 | weekdays[-1] # last element (element 4) 187 | weekdays[::2] # every 2nd element (0, 2, 4) 188 | weekdays[::-1] # backwards (4, 3, 2, 1, 0) 189 | 190 | # alternative method for returning the list backwards 191 | list(reversed(weekdays)) 192 | 193 | # sort a list in place (modifies but does not return the list) 194 | simpsons.sort() 195 | simpsons.sort(reverse=True) # sort in reverse 196 | simpsons.sort(key=len) # sort by a key 197 | 198 | # return a sorted list (does not modify the original list) 199 | sorted(simpsons) 200 | sorted(simpsons, reverse=True) 201 | sorted(simpsons, key=len) 202 | 203 | # insert into an already sorted list, and keep it sorted 204 | num = [10, 20, 40, 50] 205 | from bisect import insort 206 | insort(num, 30) 207 | 208 | # create a second reference to the same list 209 | same_num = num 210 | same_num[0] = 0 # modifies both 'num' and 'same_num' 211 | 212 | # copy a list (two ways) 213 | new_num = num[:] 214 | new_num = list(num) 215 | 216 | # examine objects 217 | num is same_num # returns True (checks whether they are the same object) 218 | num is new_num # returns False 219 | num == same_num # returns True (checks whether they have the same contents) 220 | num == new_num # returns True 221 | 222 | 223 | 224 | ### TUPLES ### 225 | ## properties: ordered, iterable, immutable, can contain multiple data types 226 | ## like lists, but they don't change size 227 | 228 | # create a tuple 229 | digits = (0, 1, 'two') # create a tuple directly 230 | digits = tuple([0, 1, 'two']) # create a tuple from a list 231 | zero = (0,) # trailing comma is required to indicate it's a tuple 232 | 233 | # examine a tuple 234 | digits[2] # returns 'two' 235 | len(digits) # returns 3 236 | digits.count(0) # counts the number of instances of that value (1) 237 | digits.index(1) # returns the index of the first instance of that value (1) 238 | 239 | # elements of a tuple cannot be modified 240 | digits[2] = 2 # throws an error 241 | 242 | # concatenate tuples 243 | digits = digits + (3, 4) 244 | 245 | # create a single tuple with elements repeated (also works with lists) 246 | (3, 4) * 2 # returns (3, 4, 3, 4) 247 | 248 | # sort a list of tuples 249 | tens = [(20, 60), (10, 40), (20, 30)] 250 | sorted(tens) # sorts by first element in tuple, then second element 251 | # returns [(10, 40), (20, 30), (20, 60)] 252 | 253 | # tuple unpacking 254 | bart = ('male', 10, 'simpson') # create a tuple 255 | (sex, age, surname) = bart # assign three values at once 256 | 257 | 258 | 259 | ### STRINGS ### 260 | ## properties: iterable, immutable 261 | 262 | # create a string 263 | s = str(42) # convert another data type into a string 264 | s = 'I like you' 265 | 266 | # examine a string 267 | s[0] # returns 'I' 268 | len(s) # returns 10 269 | 270 | # string slicing is like list slicing 271 | s[:6] # returns 'I like' 272 | s[7:] # returns 'you' 273 | s[-1] # returns 'u' 274 | 275 | # basic string methods (does not modify the original string) 276 | s.lower() # returns 'i like you' 277 | s.upper() # returns 'I LIKE YOU' 278 | s.startswith('I') # returns True 279 | s.endswith('you') # returns True 280 | s.isdigit() # returns False (returns True if every character in the string is a digit) 281 | s.find('like') # returns index of first occurrence (2), but doesn't support regex 282 | s.find('hate') # returns -1 since not found 283 | s.replace('like', 'love') # replaces all instances of 'like' with 'love' 284 | 285 | # split a string into a list of substrings separated by a delimiter 286 | s.split(' ') # returns ['I', 'like', 'you'] 287 | s.split() # equivalent (since space is the default delimiter) 288 | s2 = 'a, an, the' 289 | s2.split(',') # returns ['a', ' an', ' the'] 290 | 291 | # join a list of strings into one string using a delimiter 292 | stooges = ['larry', 'curly', 'moe'] 293 | ' '.join(stooges) # returns 'larry curly moe' 294 | 295 | # concatenate strings 296 | s3 = 'The meaning of life is' 297 | s4 = '42' 298 | s3 + ' ' + s4 # returns 'The meaning of life is 42' 299 | 300 | # remove whitespace from start and end of a string 301 | s5 = ' ham and cheese ' 302 | s5.strip() # returns 'ham and cheese' 303 | 304 | # string substitutions: all of these return 'raining cats and dogs' 305 | 'raining %s and %s' % ('cats', 'dogs') # old way 306 | 'raining {} and {}'.format('cats', 'dogs') # new way 307 | 'raining {arg1} and {arg2}'.format(arg1='cats', arg2='dogs') # named arguments 308 | 309 | # string formatting 310 | # more examples: https://mkaz.blog/code/python-string-format-cookbook/ 311 | 'pi is {:.2f}'.format(3.14159) # returns 'pi is 3.14' 312 | 313 | # normal strings versus raw strings 314 | print('first line\nsecond line') # normal strings allow for escaped characters 315 | print(r'first line\nfirst line') # raw strings treat backslashes as literal characters 316 | 317 | 318 | 319 | ### DICTIONARIES ### 320 | ## properties: unordered, iterable, mutable, can contain multiple data types 321 | ## made of key-value pairs 322 | ## keys must be unique, and can be strings, numbers, or tuples 323 | ## values can be any type 324 | 325 | # create an empty dictionary (two ways) 326 | empty_dict = {} 327 | empty_dict = dict() 328 | 329 | # create a dictionary (two ways) 330 | family = {'dad':'homer', 'mom':'marge', 'size':6} 331 | family = dict(dad='homer', mom='marge', size=6) 332 | 333 | # convert a list of tuples into a dictionary 334 | list_of_tuples = [('dad', 'homer'), ('mom', 'marge'), ('size', 6)] 335 | family = dict(list_of_tuples) 336 | 337 | # examine a dictionary 338 | family['dad'] # returns 'homer' 339 | len(family) # returns 3 340 | 'mom' in family # returns True 341 | 'marge' in family # returns False (only checks keys) 342 | 343 | # returns a list (Python 2) or an iterable view (Python 3) 344 | family.keys() # keys: ['dad', 'mom', 'size'] 345 | family.values() # values: ['homer', 'marge', 6] 346 | family.items() # key-value pairs: [('dad', 'homer'), ('mom', 'marge'), ('size', 6)] 347 | 348 | # modify a dictionary (does not return the dictionary) 349 | family['cat'] = 'snowball' # add a new entry 350 | family['cat'] = 'snowball ii' # edit an existing entry 351 | del family['cat'] # delete an entry 352 | family['kids'] = ['bart', 'lisa'] # dictionary value can be a list 353 | family.pop('dad') # remove an entry and return the value ('homer') 354 | family.update({'baby':'maggie', 'grandpa':'abe'}) # add multiple entries 355 | 356 | # access values more safely with 'get' 357 | family['mom'] # returns 'marge' 358 | family.get('mom') # equivalent 359 | family['grandma'] # throws an error since the key does not exist 360 | family.get('grandma') # returns None instead 361 | family.get('grandma', 'not found') # returns 'not found' (the default) 362 | 363 | # access a list element within a dictionary 364 | family['kids'][0] # returns 'bart' 365 | family['kids'].remove('lisa') # removes 'lisa' 366 | 367 | # string substitution using a dictionary 368 | 'youngest child is %(baby)s' % family # returns 'youngest child is maggie' 369 | 370 | 371 | 372 | ### SETS ### 373 | ## properties: unordered, iterable, mutable, can contain multiple data types 374 | ## made of unique elements (strings, numbers, or tuples) 375 | ## like dictionaries, but with keys only (no values) 376 | 377 | # create an empty set 378 | empty_set = set() 379 | 380 | # create a set 381 | languages = {'python', 'r', 'java'} # create a set directly 382 | snakes = set(['cobra', 'viper', 'python']) # create a set from a list 383 | 384 | # examine a set 385 | len(languages) # returns 3 386 | 'python' in languages # returns True 387 | 388 | # set operations 389 | languages & snakes # returns intersection: {'python'} 390 | languages | snakes # returns union: {'cobra', 'r', 'java', 'viper', 'python'} 391 | languages - snakes # returns set difference: {'r', 'java'} 392 | snakes - languages # returns set difference: {'cobra', 'viper'} 393 | 394 | # modify a set (does not return the set) 395 | languages.add('sql') # add a new element 396 | languages.add('r') # try to add an existing element (ignored, no error) 397 | languages.remove('java') # remove an element 398 | languages.remove('c') # try to remove a non-existing element (throws an error) 399 | languages.discard('c') # remove an element if present, but ignored otherwise 400 | languages.pop() # remove and return an arbitrary element 401 | languages.clear() # remove all elements 402 | languages.update(['go', 'spark']) # add multiple elements (can also pass a set) 403 | 404 | # get a sorted list of unique elements from a list 405 | sorted(set([9, 0, 2, 1, 0])) # returns [0, 1, 2, 9] 406 | 407 | 408 | 409 | ### DEFINING FUNCTIONS ### 410 | 411 | # define a function with no arguments and no return values 412 | def print_text(): 413 | print('this is text') 414 | 415 | # call the function 416 | print_text() 417 | 418 | # define a function with one argument and no return values 419 | def print_this(x): 420 | print(x) 421 | 422 | # call the function 423 | print_this(3) # prints 3 424 | n = print_this(3) # prints 3, but doesn't assign 3 to n 425 | # because the function has no return statement 426 | 427 | # define a function with one argument and one return value 428 | def square_this(x): 429 | return x**2 430 | 431 | # include an optional docstring to describe the effect of a function 432 | def square_this(x): 433 | """Return the square of a number.""" 434 | return x**2 435 | 436 | # call the function 437 | square_this(3) # prints 9 438 | var = square_this(3) # assigns 9 to var, but does not print 9 439 | 440 | # define a function with two 'positional arguments' (no default values) and 441 | # one 'keyword argument' (has a default value) 442 | def calc(a, b, op='add'): 443 | if op == 'add': 444 | return a + b 445 | elif op == 'sub': 446 | return a - b 447 | else: 448 | print('valid operations are add and sub') 449 | 450 | # call the function 451 | calc(10, 4, op='add') # returns 14 452 | calc(10, 4, 'add') # also returns 14: unnamed arguments are inferred by position 453 | calc(10, 4) # also returns 14: default for 'op' is 'add' 454 | calc(10, 4, 'sub') # returns 6 455 | calc(10, 4, 'div') # prints 'valid operations are add and sub' 456 | 457 | # use 'pass' as a placeholder if you haven't written the function body 458 | def stub(): 459 | pass 460 | 461 | # return two values from a single function 462 | def min_max(nums): 463 | return min(nums), max(nums) 464 | 465 | # return values can be assigned to a single variable as a tuple 466 | nums = [1, 2, 3] 467 | min_max_num = min_max(nums) # min_max_num = (1, 3) 468 | 469 | # return values can be assigned into multiple variables using tuple unpacking 470 | min_num, max_num = min_max(nums) # min_num = 1, max_num = 3 471 | 472 | 473 | 474 | ### ANONYMOUS (LAMBDA) FUNCTIONS ### 475 | ## primarily used to temporarily define a function for use by another function 476 | 477 | # define a function the "usual" way 478 | def squared(x): 479 | return x**2 480 | 481 | # define an identical function using lambda 482 | squared = lambda x: x**2 483 | 484 | # sort a list of strings by the last letter (without using lambda) 485 | simpsons = ['homer', 'marge', 'bart'] 486 | def last_letter(word): 487 | return word[-1] 488 | sorted(simpsons, key=last_letter) 489 | 490 | # sort a list of strings by the last letter (using lambda) 491 | sorted(simpsons, key=lambda word: word[-1]) 492 | 493 | 494 | 495 | ### FOR LOOPS AND WHILE LOOPS ### 496 | 497 | # range returns a list of integers (Python 2) or a sequence (Python 3) 498 | range(0, 3) # returns [0, 1, 2]: includes start value but excludes stop value 499 | range(3) # equivalent: default start value is 0 500 | range(0, 5, 2) # returns [0, 2, 4]: third argument is the step value 501 | 502 | # Python 2 only: use xrange to create a sequence rather than a list (saves memory) 503 | xrange(100, 100000, 5) 504 | 505 | # for loop (not the recommended style) 506 | fruits = ['apple', 'banana', 'cherry'] 507 | for i in range(len(fruits)): 508 | print(fruits[i].upper()) 509 | 510 | # for loop (recommended style) 511 | for fruit in fruits: 512 | print(fruit.upper()) 513 | 514 | # iterate through two things at once (using tuple unpacking) 515 | family = {'dad':'homer', 'mom':'marge', 'size':6} 516 | for key, value in family.items(): 517 | print(key, value) 518 | 519 | # use enumerate if you need to access the index value within the loop 520 | for index, fruit in enumerate(fruits): 521 | print(index, fruit) 522 | 523 | # for/else loop 524 | for fruit in fruits: 525 | if fruit == 'banana': 526 | print('Found the banana!') 527 | break # exit the loop and skip the 'else' block 528 | else: 529 | # this block executes ONLY if the for loop completes without hitting 'break' 530 | print("Can't find the banana") 531 | 532 | # while loop 533 | count = 0 534 | while count < 5: 535 | print('This will print 5 times') 536 | count += 1 # equivalent to 'count = count + 1' 537 | 538 | 539 | 540 | ### COMPREHENSIONS ### 541 | 542 | # for loop to create a list of cubes 543 | nums = [1, 2, 3, 4, 5] 544 | cubes = [] 545 | for num in nums: 546 | cubes.append(num**3) 547 | 548 | # equivalent list comprehension 549 | cubes = [num**3 for num in nums] # [1, 8, 27, 64, 125] 550 | 551 | # for loop to create a list of cubes of even numbers 552 | cubes_of_even = [] 553 | for num in nums: 554 | if num % 2 == 0: 555 | cubes_of_even.append(num**3) 556 | 557 | # equivalent list comprehension 558 | # syntax: [expression for variable in iterable if condition] 559 | cubes_of_even = [num**3 for num in nums if num % 2 == 0] # [8, 64] 560 | 561 | # for loop to cube even numbers and square odd numbers 562 | cubes_and_squares = [] 563 | for num in nums: 564 | if num % 2 == 0: 565 | cubes_and_squares.append(num**3) 566 | else: 567 | cubes_and_squares.append(num**2) 568 | 569 | # equivalent list comprehension (using a ternary expression) 570 | # syntax: [true_condition if condition else false_condition for variable in iterable] 571 | cubes_and_squares = [num**3 if num % 2 == 0 else num**2 for num in nums] # [1, 8, 9, 64, 25] 572 | 573 | # for loop to flatten a 2d-matrix 574 | matrix = [[1, 2], [3, 4]] 575 | items = [] 576 | for row in matrix: 577 | for item in row: 578 | items.append(item) 579 | 580 | # equivalent list comprehension 581 | items = [item for row in matrix 582 | for item in row] # [1, 2, 3, 4] 583 | 584 | # set comprehension 585 | fruits = ['apple', 'banana', 'cherry'] 586 | unique_lengths = {len(fruit) for fruit in fruits} # {5, 6} 587 | 588 | # dictionary comprehension 589 | fruit_lengths = {fruit:len(fruit) for fruit in fruits} # {'apple': 5, 'banana': 6, 'cherry': 6} 590 | fruit_indices = {fruit:index for index, fruit in enumerate(fruits)} # {'apple': 0, 'banana': 1, 'cherry': 2} 591 | 592 | 593 | 594 | ### MAP AND FILTER ### 595 | 596 | # 'map' applies a function to every element of a sequence 597 | # ...and returns a list (Python 2) or iterator (Python 3) 598 | simpsons = ['homer', 'marge', 'bart'] 599 | map(len, simpsons) # returns [5, 5, 4] 600 | map(lambda word: word[-1], simpsons) # returns ['r', 'e', 't'] 601 | 602 | # equivalent list comprehensions 603 | [len(word) for word in simpsons] 604 | [word[-1] for word in simpsons] 605 | 606 | # 'filter' returns a list (Python 2) or iterator (Python 3) containing 607 | # ...the elements from a sequence for which a condition is True 608 | nums = range(5) 609 | filter(lambda x: x % 2 == 0, nums) # returns [0, 2, 4] 610 | 611 | # equivalent list comprehension 612 | [num for num in nums if num % 2 == 0] 613 | --------------------------------------------------------------------------------