index.html 25.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="last-modified" content="2017-08-04 00:20:27 +0200">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- meta "search-domain" used for google site search function google_search() -->
    <meta name="search-domain" value="/swc-releases/2017.08/python-novice-inflammation">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="../assets/css/lesson.css" />
    
    <link rel="shortcut icon" type="image/x-icon" href="/favicon-swc.ico" />
    
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
	<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
	<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
	<![endif]-->
    <title>Programming with Python: Storing Multiple Values in Lists</title>
  </head>
  <body>
    <div class="container">
      
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>

      
      

      
      <a class="navbar-brand" href="../">Home</a>

    </div>
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">

	
        <li><a href="../conduct/">Code of Conduct</a></li>

	
        
        <li><a href="../setup/">Setup</a></li>
        <li class="dropdown">
          <a href="../" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Episodes <span class="caret"></span></a>
          <ul class="dropdown-menu">
            
            <li><a href="../01-numpy/">Analyzing Patient Data</a></li>
            
            <li><a href="../02-loop/">Repeating Actions with Loops</a></li>
            
            <li><a href="../03-lists/">Storing Multiple Values in Lists</a></li>
            
            <li><a href="../04-files/">Analyzing Data from Multiple Files</a></li>
            
            <li><a href="../05-cond/">Making Choices</a></li>
            
            <li><a href="../06-func/">Creating Functions</a></li>
            
            <li><a href="../07-errors/">Errors and Exceptions</a></li>
            
            <li><a href="../08-defensive/">Defensive Programming</a></li>
            
            <li><a href="../09-debugging/">Debugging</a></li>
            
            <li><a href="../10-cmdline/">Command-Line Programs</a></li>
            
	    <li role="separator" class="divider"></li>
            <li><a href="../aio/">All in one page (Beta)</a></li>
          </ul>
        </li>
	

	
	
        <li class="dropdown">
          <a href="../" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Extras <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="../reference/">Reference</a></li>
            
            <li><a href="../about/">About</a></li>
            
            <li><a href="../discuss/">Discussion</a></li>
            
            <li><a href="../figures/">Figures</a></li>
            
            <li><a href="../guide/">Instructor Notes</a></li>
            
          </ul>
        </li>
	

	
        <li><a href="../license/">License</a></li>
	
	<li><a href="/edit/gh-pages/_episodes/03-lists.md">Improve this page <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a></li>
	
      </ul>
      <form class="navbar-form navbar-right" role="search" id="search" onsubmit="google_search(); return false;">
        <div class="form-group">
          <input type="text" id="google-search" placeholder="Search..." aria-label="Google site search">
        </div>
      </form>
    </div>
  </div>
</nav>


<div class="row">
  <div class="col-md-1">
    <h3>
      
      <a href="../02-loop/"><span class="glyphicon glyphicon-menu-left" aria-hidden="true"></span><span class="sr-only">previous episode</span></a>
      
    </h3>
  </div>
  <div class="col-md-10">
    
    <h3 class="maintitle"><a href="../">Programming with Python</a></h3>
    
  </div>
  <div class="col-md-1">
    <h3>
      
      <a href="../04-files/"><span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span><span class="sr-only">next episode</span></a>
      
    </h3>
  </div>
</div>

<article>
<div class="row">
  <div class="col-md-1">
  </div>
  <div class="col-md-10">
    <h1 class="maintitle">Storing Multiple Values in Lists</h1>
  </div>
  <div class="col-md-1">
  </div>
</div>


<blockquote class="objectives">
  <h2>Overview</h2>

  <div class="row">
    <div class="col-md-3">
      <strong>Teaching:</strong> 30 min
      <br/>
      <strong>Exercises:</strong> 0 min
    </div>
    <div class="col-md-9">
      <strong>Questions</strong>
      <ul>
	
	<li><p>How can I store many values together?</p>
</li>
	
      </ul>
    </div>
  </div>

  <div class="row">
    <div class="col-md-3">
    </div>
    <div class="col-md-9">
      <strong>Objectives</strong>
      <ul>
	
	<li><p>Explain what a list is.</p>
</li>
	
	<li><p>Create and index lists of simple values.</p>
</li>
	
      </ul>
    </div>
  </div>

</blockquote>

<p>Just as a <code class="highlighter-rouge">for</code> loop is a way to do operations many times,
a list is a way to store many values.
Unlike NumPy arrays,
lists are built into the language (so we don’t have to load a library
to use them).
We create a list by putting values inside square brackets and separating the values with commas:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>odds = [1, 3, 5, 7]
print('odds are:', odds)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>odds are: [1, 3, 5, 7]
</code></pre>
</div>

<p>We select individual elements from lists by indexing them:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print('first and last:', odds[0], odds[-1])
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>first and last: 1 7
</code></pre>
</div>

<p>and if we loop over a list,
the loop variable is assigned elements one at a time:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>for number in odds:
    print(number)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>1
3
5
7
</code></pre>
</div>

<p>There is one important difference between lists and strings:
we can change the values in a list,
but we cannot change individual characters in a string.
For example:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>names = ['Newton', 'Darwing', 'Turing'] # typo in Darwin's name
print('names is originally:', names)
names[1] = 'Darwin' # correct the name
print('final value of names:', names)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>names is originally: ['Newton', 'Darwing', 'Turing']
final value of names: ['Newton', 'Darwin', 'Turing']
</code></pre>
</div>

<p>works, but:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>name = 'Darwin'
name[0] = 'd'
</code></pre>
</div>

<div class="error highlighter-rouge"><pre class="highlight"><code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-8-220df48aeb2e&gt; in &lt;module&gt;()
      1 name = 'Darwin'
----&gt; 2 name[0] = 'd'

TypeError: 'str' object does not support item assignment
</code></pre>
</div>

<p>does not.</p>

<blockquote class="callout">
  <h2 id="ch-ch-ch-changes">Ch-Ch-Ch-Changes</h2>

  <p>Data which can be modified in place is called <a href="../reference/#mutable">mutable</a>,
while data which cannot be modified is called <a href="../reference/#immutable">immutable</a>.
Strings and numbers are immutable. This does not mean that variables with string or number values are constants,
but when we want to change the value of a string or number variable, we can only replace the old value
with a completely new value.</p>

  <p>Lists and arrays, on the other hand, are mutable: we can modify them after they have been created. We can
change individual elements, append new elements, or reorder the whole list.  For some operations, like
sorting, we can choose whether to use a function that modifies the data in place or a function that returns a
modified copy and leaves the original unchanged.</p>

  <p>Be careful when modifying data in place.  If two variables refer to the same list, and you modify the list
value, it will change for both variables!</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>salsa = ['peppers', 'onions', 'cilantro', 'tomatoes']
mySalsa = salsa        # &lt;-- mySalsa and salsa point to the *same* list data in memory
salsa[0] = 'hot peppers'
print('Ingredients in my salsa:', mySalsa)
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>Ingredients in my salsa: ['hot peppers', 'onions', 'cilantro', 'tomatoes']
</code></pre>
  </div>

  <p>If you want variables with mutable values to be independent, you
must make a copy of the value when you assign it.</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>salsa = ['peppers', 'onions', 'cilantro', 'tomatoes']
mySalsa = list(salsa)        # &lt;-- makes a *copy* of the list
salsa[0] = 'hot peppers'
print('Ingredients in my salsa:', mySalsa)
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>Ingredients in my salsa: ['peppers', 'onions', 'cilantro', 'tomatoes']
</code></pre>
  </div>

  <p>Because of pitfalls like this, code which modifies data in place can be more difficult to understand. However,
it is often far more efficient to modify a large data structure in place than to create a modified copy for
every small change. You should consider both of these aspects when writing your code.</p>
</blockquote>

<blockquote class="callout">
  <h2 id="nested-lists">Nested Lists</h2>
  <p>Since lists can contain any Python variable, it can even contain other lists.</p>

  <p>For example, we could represent the products in the shelves of a small grocery shop:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>x = [['pepper', 'zucchini', 'onion'],
     ['cabbage', 'lettuce', 'garlic'],
     ['apple', 'pear', 'banana']]
</code></pre>
  </div>

  <p>Here is a visual example of how indexing a list of lists <code class="highlighter-rouge">x</code> works:</p>

  <p><a href="https://twitter.com/hadleywickham/status/643381054758363136">
<img src="../fig/indexing_lists_python.png" alt="The first element of a list. Adapted from @hadleywickham's tweet about R lists." /></a></p>

  <p>Using the previously declared list <code class="highlighter-rouge">x</code>, these would be the results of the
index operations shown in the image:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>print([x[0]])
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>[['pepper', 'zucchini', 'onion']]
</code></pre>
  </div>

  <div class="python highlighter-rouge"><pre class="highlight"><code>print(x[0])
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>['pepper', 'zucchini', 'onion']
</code></pre>
  </div>

  <div class="python highlighter-rouge"><pre class="highlight"><code>print(x[0][0])
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>'pepper'
</code></pre>
  </div>

  <p>Thanks to <a href="https://twitter.com/hadleywickham/status/643381054758363136">Hadley Wickham</a>
for the image above.</p>
</blockquote>

<p>There are many ways to change the contents of lists besides assigning new values to
individual elements:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>odds.append(11)
print('odds after adding a value:', odds)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>odds after adding a value: [1, 3, 5, 7, 11]
</code></pre>
</div>

<div class="python highlighter-rouge"><pre class="highlight"><code>del odds[0]
print('odds after removing the first element:', odds)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>odds after removing the first element: [3, 5, 7, 11]
</code></pre>
</div>

<div class="python highlighter-rouge"><pre class="highlight"><code>odds.reverse()
print('odds after reversing:', odds)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>odds after reversing: [11, 7, 5, 3]
</code></pre>
</div>

<p>While modifying in place, it is useful to remember that Python treats lists in a slightly counter-intuitive way.</p>

<p>If we make a list and (attempt to) copy it then modify in place, we can cause all sorts of trouble:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>odds = [1, 3, 5, 7]
primes = odds
primes.append(2)
print('primes:', primes)
print('odds:', odds)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7, 2]
</code></pre>
</div>

<p>This is because Python stores a list in memory, and then can use multiple names to refer to the same list.
If all we want to do is copy a (simple) list, we can use the <code class="highlighter-rouge">list</code> function, so we do not modify a list we did not mean to:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>odds = [1, 3, 5, 7]
primes = list(odds)
primes.append(2)
print('primes:', primes)
print('odds:', odds)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7]
</code></pre>
</div>

<p>This is different from how variables worked in lesson 1, and more similar to how a spreadsheet works.</p>

<blockquote class="challenge">
  <h2 id="turn-a-string-into-a-list">Turn a String Into a List</h2>

  <p>Use a for-loop to convert the string “hello” into a list of letters:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>["h", "e", "l", "l", "o"]
</code></pre>
  </div>

  <p>Hint: You can create an empty list like this:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>my_list = []
</code></pre>
  </div>

  <blockquote class="solution">
    <h2 id="solution">Solution</h2>
    <div class="python highlighter-rouge"><pre class="highlight"><code>my_list = []
for char in "hello":
    my_list.append(char)
print(my_list)
</code></pre>
    </div>
  </blockquote>
</blockquote>

<p>Subsets of lists and strings can be accessed by specifying ranges of values in brackets,
similar to how we accessed ranges of positions in a Numpy array.
This is commonly referred to as “slicing” the list/string.</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>binomial_name = "Drosophila melanogaster"
group = binomial_name[0:10]
print("group:", group)

species = binomial_name[11:24]
print("species:", species)

chromosomes = ["X", "Y", "2", "3", "4"]
autosomes = chromosomes[2:5]
print("autosomes:", autosomes)

last = chromosomes[-1]
print("last:", last)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>group: Drosophila
species: melanogaster
autosomes: ["2", "3", "4"]
last: 4
</code></pre>
</div>

<blockquote class="challenge">
  <h2 id="slicing-from-the-end">Slicing From the End</h2>

  <p>Use slicing to access only the last four characters of a string or entries of a list.</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>string_for_slicing = "Observation date: 02-Feb-2013"
list_for_slicing = [["fluorine", "F"], ["chlorine", "Cl"], ["bromine", "Br"], ["iodine", "I"], ["astatine", "At"]]
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>"2013"
[["chlorine", "Cl"], ["bromine", "Br"], ["iodine", "I"], ["astatine", "At"]]
</code></pre>
  </div>

  <p>Would your solution work regardless of whether you knew beforehand
the length of the string or list
(e.g. if you wanted to apply the solution to a set of lists of different lengths)?
If not, try to change your approach to make it more robust.</p>

  <blockquote class="solution">
    <h2 id="solution-1">Solution</h2>
    <p>Use negative indices to count elements from the end of a container (such as list or string):</p>

    <div class="python highlighter-rouge"><pre class="highlight"><code>string_for_slicing[-4:]
list_for_slicing[-4:]
</code></pre>
    </div>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="non-continuous-slices">Non-Continuous Slices</h2>

  <p>So far we’ve seen how to use slicing to take single blocks
of successive entries from a sequence.
But what if we want to take a subset of entries
that aren’t next to each other in the sequence?</p>

  <p>You can achieve this by providing a third argument
to the range within the brackets, called the <em>step size</em>.
The example below shows how you can take every third entry in a list:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
subset = primes[0:12:3]
print("subset", subset)
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>subset [2, 7, 17, 29]
</code></pre>
  </div>

  <p>Notice that the slice taken begins with the first entry in the range,
followed by entries taken at equally-spaced intervals (the steps) thereafter.
If you wanted to begin the subset with the third entry,
you would need to specify that as the starting point of the sliced range:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
subset = primes[2:12:3]
print("subset", subset)
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>subset [5, 13, 23, 37]
</code></pre>
  </div>

  <p>Use the step size argument to create a new string
that contains only every other character in the string
“In an octopus’s garden in the shade”</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>beatles = "In an octopus's garden in the shade"
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>I notpssgre ntesae
</code></pre>
  </div>

  <blockquote class="solution">
    <h2 id="solution-2">Solution</h2>
    <p>To obtain every other character you need to provide a slice with the step
size of 2:</p>

    <div class="python highlighter-rouge"><pre class="highlight"><code>beatles[0:35:2]
</code></pre>
    </div>

    <p>You can also leave out the beginning and end of the slice to take the whole string
and provide only the step argument to go every second
element:</p>

    <div class="python highlighter-rouge"><pre class="highlight"><code>beatles[::2]
</code></pre>
    </div>
  </blockquote>
</blockquote>

<p>If you want to take a slice from the beginning of a sequence, you can omit the first index in the range:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>date = "Monday 4 January 2016"
day = date[0:6]
print("Using 0 to begin range:", day)
day = date[:6]
print("Omitting beginning index:", day)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>Using 0 to begin range: Monday
Omitting beginning index: Monday
</code></pre>
</div>

<p>And similarly, you can omit the ending index in the range to take a slice to the very end of the sequence:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
sond = months[8:12]
print("With known last position:", sond)
sond = months[8:len(months)]
print("Using len() to get last entry:", sond)
sond = months[8:]
print("Omitting ending index:", sond)
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>With known last position: ["sep", "oct", "nov", "dec"]
Using len() to get last entry: ["sep", "oct", "nov", "dec"]
Omitting ending index: ["sep", "oct", "nov", "dec"]
</code></pre>
</div>

<blockquote class="challenge">
  <h2 id="swapping-the-contents-of-variables">Swapping the contents of variables</h2>

  <p>Explain what the overall effect of this code is:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>left = 'L'
right = 'R'

temp = left
left = right
right = temp
</code></pre>
  </div>

  <p>Compare it to:</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>left, right = [right, left]
</code></pre>
  </div>

  <p>Do they always do the same thing?
Which do you find easier to read?</p>

  <blockquote class="solution">
    <h2 id="solution-3">Solution</h2>
    <p>Both examples exchange the values of <code class="highlighter-rouge">left</code> and <code class="highlighter-rouge">right</code>:</p>

    <div class="python highlighter-rouge"><pre class="highlight"><code>print(left, right)
</code></pre>
    </div>

    <div class="output highlighter-rouge"><pre class="highlight"><code>R L
</code></pre>
    </div>

    <p>In the first case we used a temporary variable <code class="highlighter-rouge">temp</code> to keep the value of <code class="highlighter-rouge">left</code> before we overwrite it with the value of <code class="highlighter-rouge">right</code>. In the second case, <code class="highlighter-rouge">right</code> and <code class="highlighter-rouge">left</code> are packed into a list and then unpacked into <code class="highlighter-rouge">left</code> and <code class="highlighter-rouge">right</code>.</p>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="overloading">Overloading</h2>

  <p><code class="highlighter-rouge">+</code> usually means addition, but when used on strings or lists, it means “concatenate”.
Given that, what do you think the multiplication operator <code class="highlighter-rouge">*</code> does on lists?
In particular, what will be the output of the following code?</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>counts = [2, 4, 6, 8, 10]
repeats = counts * 2
print(repeats)
</code></pre>
  </div>

  <ol>
    <li><code class="highlighter-rouge">[2, 4, 6, 8, 10, 2, 4, 6, 8, 10]</code></li>
    <li><code class="highlighter-rouge">[4, 8, 12, 16, 20]</code></li>
    <li><code class="highlighter-rouge">[[2, 4, 6, 8, 10],[2, 4, 6, 8, 10]]</code></li>
    <li><code class="highlighter-rouge">[2, 4, 6, 8, 10, 4, 8, 12, 16, 20]</code></li>
  </ol>

  <p>The technical term for this is <em>operator overloading</em>:
a single operator, like <code class="highlighter-rouge">+</code> or <code class="highlighter-rouge">*</code>,
can do different things depending on what it’s applied to.</p>

  <blockquote class="solution">
    <h2 id="solution-4">Solution</h2>

    <p>The multiplication operator <code class="highlighter-rouge">*</code> used on a list replicates elements of the list and concatenates them together:</p>

    <div class="output highlighter-rouge"><pre class="highlight"><code>[2, 4, 6, 8, 10, 2, 4, 6, 8, 10]
</code></pre>
    </div>

    <p>It’s equivalent to:</p>

    <div class="python highlighter-rouge"><pre class="highlight"><code>counts + counts
</code></pre>
    </div>
  </blockquote>
</blockquote>


<blockquote class="keypoints">
  <h2>Key Points</h2>
  <ul>
    
    <li><p><code class="highlighter-rouge">[value1, value2, value3, ...]</code> creates a list.</p>
</li>
    
    <li><p>Lists are indexed and sliced in the same way as strings and arrays.</p>
</li>
    
    <li><p>Lists are mutable (i.e., their values can be changed in place).</p>
</li>
    
    <li><p>Strings are immutable (i.e., the characters in them cannot be changed).</p>
</li>
    
  </ul>
</blockquote>

</article>

<div class="row">
  <div class="col-md-1">
    <h3>
      
      <a href="../02-loop/"><span class="glyphicon glyphicon-menu-left" aria-hidden="true"></span><span class="sr-only">previous episode</span></a>
      
    </h3>
  </div>
  <div class="col-md-10">
    
  </div>
  <div class="col-md-1">
    <h3>
      
      <a href="../04-files/"><span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span><span class="sr-only">next episode</span></a>
      
    </h3>
  </div>
</div>


      
      
<footer>
  <div class="row">
    <div class="col-md-6" align="left">
      <h4>
	Copyright &copy; 2016–2017
	
	<a href="https://software-carpentry.org">Software Carpentry Foundation</a>
	
      </h4>
    </div>
    <div class="col-md-6" align="right">
      <h4>
	
	<a href="/edit/gh-pages/_episodes/03-lists.md">Edit on GitHub</a>
	
	/
	<a href="/blob/gh-pages/CONTRIBUTING.md">Contributing</a>
	/
	<a href="/">Source</a>
	/
	<a href="/blob/gh-pages/CITATION">Cite</a>
	/
	<a href="">Contact</a>
      </h4>
    </div>
  </div>
</footer>

      
    </div>
    
<script src="../assets/js/jquery.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/lesson.js"></script>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-37305346-2', 'auto');
  ga('send', 'pageview');
</script>

  </body>
</html>