{"id":1689,"date":"2011-04-16T15:21:55","date_gmt":"2011-04-16T15:21:55","guid":{"rendered":"http:\/\/cemclinux1.math.uwaterloo.ca\/~cscircles\/wordpress\/?page_id=1689"},"modified":"2011-04-16T15:21:55","modified_gmt":"2011-04-16T15:21:55","slug":"13-lists","status":"publish","type":"page","link":"https:\/\/olescs.hkmu.edu.hk\/python\/13-lists\/","title":{"rendered":"13: Lists (Arrays)"},"content":{"rendered":"<!-- Please retain this notice and add more notes if you create a new version.<br \/>\nOriginal lesson author: David Pritchard, daveagp@gmail.com, http:\/\/cscircles.ca<br \/>\nLicense: http:\/\/creativecommons.org\/licenses\/by-nc-sa\/3.0\/-->\n<p>A <strong>list<\/strong> is a sequence of several variables, grouped together under a single name. Instead of writing a program with many variables <code>x0<\/code>, <code>x1<\/code>, <code>x2<\/code>, \u2026 you can define a single variable <code>x<\/code> and access its members <code>x[0]<\/code>, <code>x[1]<\/code>, <code>x[2]<\/code>, etc. More importantly, you can put other expressions and variables inside the square brackets, like <code>x[i]<\/code> and <code>x[i+1]<\/code>. This allows us to deal with arbitrarily large data sets using just a single small piece of code.<\/p>\n<p>One way to create a list is by enclosing several values, separated with commas, between square brackets:<\/p>\n<pre>myList = [\"the first value in the list\", 1999, 4.5]<\/pre>This creates a list called\u00a0<code>myList<\/code> of length 3. Each element of the list gets a number called its\u00a0<strong>index<\/strong>: the initial element has index 0, the next element has index 1, and so forth. The individual variables comprising the list have the names<\/p>\n<p style=\"text-align: center\"><code>\u00ablistName\u00bb[\u00abindexNumber\u00bb]<\/code><\/p>\n<p>So in this example, <code>myList[0]<\/code> is a variable whose value is the string\u00a0<code>\"the first value in the list\"<\/code> and <code>print(myList[2])<\/code> <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=myList%20%3D%20%5B%22the%20first%20value%20in%20the%20list%22%2C%201999%2C%204.5%5D%0Aprint%28myList%5B2%5D%29\" target=\"_blank\">would print<\/a> <code>4.5<\/code>. You can also change the values of items in the list, and print out entire lists:<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform0\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox0'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Updating and printing a list.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 84px;'><textarea wrap='off' name='usercode0' id='usercode0'  cols=10 rows=3 readonly='readonly'  style = 'height : 84px;'  class='pyboxCode RO'>\nnumbers = ['zero', 'one', 'two']\nnumbers[0] = 'zilch'\nprint(numbers)<\/textarea><\/div>\n<div id='pbhistory0' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit0' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(0)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(0,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse0\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"0\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"d82a0deb4b4717421add40670f2e07b9\"\/>\n<div id='pbresults0' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit0\").value = \"Run program\";document.getElementById(\"inputInUse0\").value = \"N\";<\/script>\n<\/p>\n<p>As you can see, <code>numbers[0]<\/code> is treated as if it were itself a variable: it has a value and can be changed.<\/p>\n<p>Next, try to predict the final state of the visualized example below, then compare it with actually running the code.<\/p>\n<p><iframe width='100%' height='480' frameborder='0' scrolling='no' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/OnlinePythonTutor3-cemc\/iframe-embed.html#code=myList+%3D+%5B1%2C+10%2C+100%2C+1000%5D%0Afor+i+in+range%280%2C+2%29%3A%0A++myList%5Bi%5D+%3D+2%2AmyList%5Bi%5D%2Bi&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=0&resizeContainer=true&highlightLines&width=350&rightStdout=1'><\/iframe><\/p>\n<div class='pybox modeNeutral' id='pybox1'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Multiple Choice Exercise: <\/span><span class='title'>Meta-Stuff<\/span><\/div><div>What is the output of the following code fragment? <\/p>\n<pre>stuff = [2, 25, 80, 12]<br\/>stuff[stuff[0]] = stuff[3]<br\/>print(stuff)<\/pre> <\/div><label>Your choice: <\/label><select id=\"pyselect1\"><option value=\"d\" selected>Select one<\/option><option value=\"w\">[2, 25, 80, 80]<\/option><option value=\"w\">This code fragment causes an error.<\/option><option value=\"r\">[2, 25, 12, 12]<\/option><option value=\"w\">[12, 25, 80, 12]<\/option><option value=\"w\">[2, 25, 80, 12]<\/option><\/select><div class='pyboxbuttons'><input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" name=\"slug\" value=\"13.indexindex\"\/><input type='submit' style='margin:5px;' value='Check answer' onClick='pbMultiCheck(1)'\/><\/div><div class=\"pbresults\" id=\"pyMultiResults1\"><\/div><div class=\"epilogue\">Correct! Look at the assignment statement (the 2nd line). The value of <code>stuff[3]<\/code> on the right side is <code>12<\/code>. For the left side, <code>stuff[0]<\/code> is <code>2<\/code>, so <code>stuff[stuff[0]]<\/code> refers to the variable <code>stuff[2]<\/code>. The value of this variable is updated (from <code>80<\/code>) to <code>12<\/code>.<\/div><\/div>\n<p><table class='pywarn'><tr><td class='pywarnleft'><img src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/warning.png'\/><\/td><td class='pywarnright'><span> What Python calls a\u00a0<strong>list<\/strong> would be called an\u00a0<strong>array<\/strong> in most other programming languages. Python also has\u00a0<a href=\"http:\/\/docs.python.org\/py3k\/library\/array.html\">something<\/a> different &amp; more advanced called arrays. <\/span><\/td><\/table><\/p>\n<h3>A Common Error<\/h3>\n<p>If you try to ask Python for an index that doesn't exist, it gives you an error:<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform2\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox2'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Out-of-range error.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 58px;'><textarea wrap='off' name='usercode2' id='usercode2'  cols=10 rows=2 readonly='readonly'  style = 'height : 58px;'  class='pyboxCode RO'>\nmyList=[1, 2, 4, 8]\nprint(myList[4])<\/textarea><\/div>\n<div id='pbhistory2' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit2' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(2)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(2,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse2\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"2\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"d236bc08f9f6bf1c1ceac57fa1675129\"\/>\n<div id='pbresults2' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit2\").value = \"Run program\";document.getElementById(\"inputInUse2\").value = \"N\";<\/script>\n<\/p>\n<p>In the above example, because\u00a0<code>myList<\/code> has length 4 and the first index is 0, the maximum possible index is 3. Asking for an index of 4, 5, or anything larger gives this kind of error.<\/p>\n<p><span style=\"color: #000000;font-size: 23px;line-height: 35px\">Common Useful Operations<\/span><\/p>\n<h3>The Length of a List: <code>len(\u00ablist\u00bb)<\/code><\/h3>\n<p>To determine the number of items in a list, call the function <code>len()<\/code> on that list. Look at how <code>range<\/code> is used in the following example.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform3\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox3'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Getting the length of a list and using it to iterate through the list.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 110px;'><textarea wrap='off' name='usercode3' id='usercode3'  cols=10 rows=4 readonly='readonly'  style = 'height : 110px;'  class='pyboxCode RO'>\nmyList = [3, 12, \"pizza\", 3, 4]\nprint(\"myList has length\", len(myList))\nfor i in range(0, len(myList)):\n  print(\"item at index\", i, \":\", myList[i])<\/textarea><\/div>\n<div id='pbhistory3' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit3' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(3)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(3,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse3\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"3\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"f3dbb38901f088264cb9c514967aa74e\"\/>\n<div id='pbresults3' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit3\").value = \"Run program\";document.getElementById(\"inputInUse3\").value = \"N\";<\/script>\n<\/p>\n<p>It is common to use <code>len<\/code> to write code that can work on lists of any length, like in the example above, and in the next exercise.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform4\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox4'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Coding Exercise: <\/span><span class='title'>Monkey in the Middle<\/span><\/div>Write a function\u00a0<code>middle(L)<\/code> which takes a list <code>L<\/code> as its argument, and returns the item in the <em>middle<\/em> position of <code>L<\/code>. (In order that the middle is well-defined, you should assume that <code>L<\/code> has odd length.) For example, calling <code>middle([8, 0, 100, 12, 1])<\/code> should return <code>100<\/code>, since it is positioned exactly in the middle of the list.<div class=\"helpOuter\" style=\"display: none;\"><div class=\"helpInner\"><div style=\"text-align: center\">You need to create an account and log in to ask a question.<\/div><\/div><\/div><div class='pyboxTextwrap pyboxCodewrap RW resizy'  style='height: 526px;'><textarea wrap='off' name='usercode4' id='usercode4'  cols=10 rows=20   class='pyboxCode RW'>\ndef...\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory4' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput4\">Enter testing statements like <code>print(myfunction(\"test argument\"))<\/code> below.<div class=\"pyboxTextwrap resizy\" style=\"height: 102px;\" ><textarea wrap=\"off\" name=\"userinput\" class=\"pyboxInput\" cols=10 rows=4><\/textarea><\/div><\/div>\n<input type='hidden' id='defaultCode4' value='def...\\n'><\/input>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit4' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch4\" value=\"Input Switch\" onclick=\"pbInputSwitch(4,'Y')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(4)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(4,'Y')\" ><\/td>\n<\/tr><\/table><select id='pbSelect4' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(4,'13.middle')\" >History<\/option>\n<option name='default' data-pbonclick=\"pbSetText(4,descape($('#defaultCode4').val()))\" >Reset code to default<\/option>\n<option name='help' data-pbonclick=\"helpClick(4);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse4\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"4\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"378144365f3118ad432dc4c1eb3ef2ab\"\/>\n<div id='pbresults4' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>jQuery(function(){pbToggleCodeMirror(4);});pbInputSwitch(4,\"Y\");<\/script>\n<\/p>\n<h3>Are Lists Like Strings?<\/h3>\n<p>At this point, you might have noticed that the operations on lists are a lot like strings: both of them can be passed to the <code>len()<\/code> function to get their lengths, and both of them use <code>X[\u00abindex\u00bb]<\/code> to extract individual items. Lists and strings are indeed related: they are both \"<a href=\"http:\/\/docs.python.org\/py3k\/library\/stdtypes.html?highlight=sequence#sequence-types-str-bytes-bytearray-list-tuple-range\">sequence types<\/a>\" in Python. The one major difference is that individual characters in strings cannot be changed.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform5\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox5'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Error caused by trying to assign a value to a character in a string.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 84px;'><textarea wrap='off' name='usercode5' id='usercode5'  cols=10 rows=3 readonly='readonly'  style = 'height : 84px;'  class='pyboxCode RO'>\nword='slack'\nprint(word, word[1])\nword[1]='n'<\/textarea><\/div>\n<div id='pbhistory5' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit5' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(5)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(5,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse5\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"5\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"071e91b26fabcbb7947f2acafc8ec3ec\"\/>\n<div id='pbresults5' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit5\").value = \"Run program\";document.getElementById(\"inputInUse5\").value = \"N\";<\/script>\n<\/p>\n<p>For this reason lists are called a <em>mutable<\/em> type and strings are <em>immutable<\/em>; you will see a little more information about this in lesson 17.<\/p>\n<h3>Concatenation and Creation<\/h3>\n<p>From the <a href=\"\/7a-strings\/\">lesson<\/a> about the <code>str<\/code> type, you may remember that it is possible to use <code>+<\/code> to merge (<em>concatenate<\/em>) two strings together. You can do the same thing with lists:<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform6\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox6'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Combining lists with <code>+<\/code>.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 136px;'><textarea wrap='off' name='usercode6' id='usercode6'  cols=10 rows=5 readonly='readonly'  style = 'height : 136px;'  class='pyboxCode RO'>\nlistA = [3, 'go', 7.1]\nlistB = [4, 'hi', 1]\nlistC = listA + listB\nprint(len(listC))\nprint(listC)<\/textarea><\/div>\n<div id='pbhistory6' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit6' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(6)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(6,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse6\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"6\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"9de0c01c5030f213b37d8ba3491ec8f8\"\/>\n<div id='pbresults6' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit6\").value = \"Run program\";document.getElementById(\"inputInUse6\").value = \"N\";<\/script>\n<\/p>\n<p>Similarly, you can use the multiplication symbol <code>*<\/code> to extend a list by repetition. This is useful for creating a new list of a desired length.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform7\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox7'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Using\u00a0<code><code>*<\/code><\/code>.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 110px;'><textarea wrap='off' name='usercode7' id='usercode7'  cols=10 rows=4 readonly='readonly'  style = 'height : 110px;'  class='pyboxCode RO'>\nmyPhoneNumber = [9, 6, 7] + [1]*4\nprint(myPhoneNumber)\nnewEmptyList = [0]*20\nprint(newEmptyList)<\/textarea><\/div>\n<div id='pbhistory7' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit7' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(7)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(7,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse7\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"7\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"b3108d3ef8326dc1609d500870b8d584\"\/>\n<div id='pbresults7' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit7\").value = \"Run program\";document.getElementById(\"inputInUse7\").value = \"N\";<\/script>\n<\/p>\n<p>To solve the next exercise, use one of the operators we just introduced, and a\u00a0<code>for<\/code> loop.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform8\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox8'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Coding Exercise: <\/span><span class='title'>It's Natural<\/span><\/div>Write a function <code>naturalNumbers<\/code> which takes a positive integer <code>n<\/code> as input, and returns a list <code>[1, 2, ...]<\/code> consisting of the first <code>n<\/code> natural numbers.<div class=\"helpOuter\" style=\"display: none;\"><div class=\"helpInner\"><div style=\"text-align: center\">You need to create an account and log in to ask a question.<\/div><\/div><\/div><div class='pyboxTextwrap pyboxCodewrap RW resizy'  style='height: 526px;'><textarea wrap='off' name='usercode8' id='usercode8'  cols=10 rows=20   class='pyboxCode RW'>\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory8' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput8\">Enter testing statements like <code>print(myfunction(\"test argument\"))<\/code> below.<div class=\"pyboxTextwrap resizy\" style=\"height: 102px;\" ><textarea wrap=\"off\" name=\"userinput\" class=\"pyboxInput\" cols=10 rows=4><\/textarea><\/div><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit8' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch8\" value=\"Input Switch\" onclick=\"pbInputSwitch(8,'Y')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(8)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(8,'Y')\" ><\/td>\n<\/tr><\/table><select id='pbSelect8' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(8,'13.natural')\" >History<\/option>\n<option name='help' data-pbonclick=\"helpClick(8);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse8\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"8\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"29cf97d65c103ebdcb24797b00634ac2\"\/>\n<div id='pbresults8' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>jQuery(function(){pbToggleCodeMirror(8);});pbInputSwitch(8,\"Y\");<\/script>\n<\/p>\n<h3>End of the Line: Negative Indices<\/h3>\n<p>To get the last item of a list, use<\/p>\n<p style=\"text-align: center\"><code>\u00ablistName\u00bb[-1]<\/code><\/p>\n<p>More generally, <code>L[-k]<\/code> returns the <code>k<\/code>th item from the end of the list; Python handles this internally by translating it to <code>L[len(L)-k]<\/code>. This shortcut notation works for strings too!<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform9\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox9'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Coding Exercise: <\/span><span class='title'>Palindrome<\/span><\/div>A <em>palindrome<\/em> is a word which is spelled the same forwards as backwards. For example, the word <\/p>\n<p style=\"text-align: center\"><code>racecar<\/code><\/p>\n<p> is a palindrome: the first and last letters are the same (r), the second and second-last letters are the same (a), etc. Write a function\u00a0<code>isPalindrome(S)<\/code> which takes a string <code>S<\/code> as input, and returns <code>True<\/code> if the string is a palindrome, and <code>False<\/code> otherwise.<div class=\"helpOuter\" style=\"display: none;\"><div class=\"helpInner\"><div style=\"text-align: center\">You need to create an account and log in to ask a question.<\/div><\/div><\/div><div class='pyboxTextwrap pyboxCodewrap RW resizy'  style='height: 526px;'><textarea wrap='off' name='usercode9' id='usercode9'  cols=10 rows=20   class='pyboxCode RW'>\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory9' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput9\">Enter testing statements like <code>print(myfunction(\"test argument\"))<\/code> below.<div class=\"pyboxTextwrap resizy\" style=\"height: 102px;\" ><textarea wrap=\"off\" name=\"userinput\" class=\"pyboxInput\" cols=10 rows=4><\/textarea><\/div><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit9' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch9\" value=\"Input Switch\" onclick=\"pbInputSwitch(9,'Y')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(9)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(9,'Y')\" ><\/td>\n<\/tr><\/table><select id='pbSelect9' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(9,'13.palindrome')\" >History<\/option>\n<option name='help' data-pbonclick=\"helpClick(9);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse9\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"9\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"2532bbb1724ba0f361a0f2cee3cfe648\"\/>\n<div id='pbresults9' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>jQuery(function(){pbToggleCodeMirror(9);});pbInputSwitch(9,\"Y\");<\/script>\n<\/p>\n<h3><code>max<\/code> and <code>sum<\/code><\/h3>\n<p>The function <code>max<\/code> which we saw before can also be applied to a list of numbers: it returns the largest number in the list. Likewise, the function <code>sum(L)<\/code> returns the sum of the elements in list <code>L<\/code>.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform10\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox10'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div><div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 84px;'><textarea wrap='off' name='usercode10' id='usercode10'  cols=10 rows=3 readonly='readonly'  style = 'height : 84px;'  class='pyboxCode RO'>\nlist = [3, 10, 4, 9, 0]\nprint(sum(list))\nprint(max(list))<\/textarea><\/div>\n<div id='pbhistory10' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit10' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(10)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(10,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse10\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"10\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"8391f798f13bdcc5e3debef1c0636f8c\"\/>\n<div id='pbresults10' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit10\").value = \"Run program\";document.getElementById(\"inputInUse10\").value = \"N\";<\/script>\n<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform11\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox11'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Coding Exercise: <\/span><span class='title'>Product<\/span><\/div>Define a function <code>prod(L)<\/code> which returns the product of the elements in a list <code>L<\/code>.<div class=\"helpOuter\" style=\"display: none;\"><div class=\"helpInner\"><div style=\"text-align: center\">You need to create an account and log in to ask a question.<\/div><\/div><\/div><div class='pyboxTextwrap pyboxCodewrap RW resizy'  style='height: 526px;'><textarea wrap='off' name='usercode11' id='usercode11'  cols=10 rows=20   class='pyboxCode RW'>\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory11' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput11\">Enter testing statements like <code>print(myfunction(\"test argument\"))<\/code> below.<div class=\"pyboxTextwrap resizy\" style=\"height: 102px;\" ><textarea wrap=\"off\" name=\"userinput\" class=\"pyboxInput\" cols=10 rows=4><\/textarea><\/div><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit11' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch11\" value=\"Input Switch\" onclick=\"pbInputSwitch(11,'Y')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(11)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(11,'Y')\" ><\/td>\n<\/tr><\/table><select id='pbSelect11' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(11,'13.product')\" >History<\/option>\n<option name='help' data-pbonclick=\"helpClick(11);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse11\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"11\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"950b81c2774eed4e8ee18e6885d7450c\"\/>\n<div id='pbresults11' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>jQuery(function(){pbToggleCodeMirror(11);});pbInputSwitch(11,\"Y\");<\/script>\n<\/p>\n<h3>Looping through lists<\/h3>\n<p>It is very common (like in the previous exercise) to loop through every value in a list. Python allows a shortcut to perform this type of an operation, usually called a <em>\"for all\" loop<\/em>\u00a0or a <em>\"for each\" loop<\/em>. Specifically, when L is a list, this code<\/p>\n<pre>for x in L:\n  \u00abloop body block\u00bb<\/pre>does the following: first <code>x<\/code> is set to the first value in <code>L<\/code> and the body is executed; then <code>x<\/code> is set to the second value in <code>L<\/code> and the body is executed; this is continued for all items in <code>L<\/code>.<\/p>\n<p>Here is a visualized example of printing out the elements in a list:<\/p>\n<p><iframe width='100%' height='480' frameborder='0' scrolling='no' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/OnlinePythonTutor3-cemc\/iframe-embed.html#code=message%3D%5B%27s%27%2C+%27o%27%2C+%27s%27%5D%0Afor+x+in+message%3A%0A++print%28x%29&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=0&resizeContainer=true&highlightLines&width=400&rightStdout=1'><\/iframe><\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform12\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox12'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Coding Exercise: <\/span><span class='title'><code>for in<\/code><\/span><\/div>Define the function\u00a0<code>prod(L)<\/code> as before, but this time using the new kind of loop.<div class=\"helpOuter\" style=\"display: none;\"><div class=\"helpInner\"><div style=\"text-align: center\">You need to create an account and log in to ask a question.<\/div><\/div><\/div><div class='pyboxTextwrap pyboxCodewrap RW resizy'  style='height: 526px;'><textarea wrap='off' name='usercode12' id='usercode12'  cols=10 rows=20   class='pyboxCode RW'>\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory12' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput12\">Enter testing statements like <code>print(myfunction(\"test argument\"))<\/code> below.<div class=\"pyboxTextwrap resizy\" style=\"height: 102px;\" ><textarea wrap=\"off\" name=\"userinput\" class=\"pyboxInput\" cols=10 rows=4><\/textarea><\/div><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit12' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch12\" value=\"Input Switch\" onclick=\"pbInputSwitch(12,'Y')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(12)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(12,'Y')\" ><\/td>\n<\/tr><\/table><select id='pbSelect12' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(12,'13.foreach')\" >History<\/option>\n<option name='help' data-pbonclick=\"helpClick(12);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse12\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"12\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"9ce3c28d9fba6297a35bc9d80720b66a\"\/>\n<div id='pbresults12' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>jQuery(function(){pbToggleCodeMirror(12);});pbInputSwitch(12,\"Y\");<\/script>\n<\/p>\n<p>\"For all\" loops work for strings too: try\u00a0<code><a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=for%20char%20in%20%22hello%22%3A%20print%28char%29\" target=\"_blank\">for char in \"hello\"<\/a><\/code>.<\/p>\n<p><em>Well done! you can proceed to the next lesson, or try some bonus exercises below.<\/em><\/p>\n<hr \/>\n<p><div class='pybox modeNeutral' id='pybox13'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Short Answer Exercise: <\/span><span class='title'>Mystery Function<\/span><\/div>What is the value of <code>x<\/code> which will cause <code>mystery(x)<\/code> to run forever? <\/p>\n<pre>def mystery(x):<br\/>  a = [0, 4, 0, 3, 2]<br\/>  while x &gt; 0:<br\/>    x = a[x]<br\/>  return \"Done\"<\/pre><label for=\"pyShortAnswer13\">Your answer: <\/label><input type=\"text\" onkeypress=\"{if (event.keyCode==13) pbShortCheck(13)}\" id=\"pyShortAnswer13\"><div class=\"pyboxbuttons\"><input type=\"hidden\" name=\"type\" value=\"trimmableString\"\/><input type=\"hidden\" name=\"correct\" value=\"3\"\/><input type=\"hidden\" name=\"slug\" value=\"13.mystery\"\/><input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type='submit' style='margin:5px;' value='Check answer' onClick = 'pbShortCheck(13)'\/><\/div><div class=\"pbresults\" id=\"pyShortResults13\"><\/div><div class=\"epilogue\">Correct!<\/div><\/div>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform14\" method=\"POST\">\n<div class='pybox modeNeutral scramble' id='pybox14'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Scramble Exercise: <\/span><span class='title'>\u00e0 la Mode<\/span><\/div>The <em>mode<\/em> of a list is the element which occurs most frequently (the one which appears the maximum number of times). Unscramble the following program so that <code>mode(L)<\/code> correctly finds the mode, assuming <code>L<\/code> is a list of numbers from 0 to 9. (On our tests, there won't be two numbers tied for the maximum frequency.) <ul class=\"pyscramble\" name=\"pyscramble\" id=\"pyscramble14\">\n <li class=\"pyscramble\">  frequency = [0]*10<\/li>\n <li class=\"pyscramble\">    frequency[i] = frequency[i] + 1<\/li>\n <li class=\"pyscramble\">    if frequency[i]==max(frequency):<\/li>\n <li class=\"pyscramble\">  for i in L:<\/li>\n <li class=\"pyscramble\">  for i in range(0, 10):<\/li>\n <li class=\"pyscramble\">      return i<\/li>\n <li class=\"pyscramble\">def mode(L):<\/li>\n<\/ul>\n<input type='hidden' id='usercode14' name='usercode14'\/>\n<div id='pbhistory14' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit14' value=' '\/><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse14\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"14\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"eb28fafe2e15b7d63b2120819163c0b8\"\/>\n<div id='pbresults14' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit14\").value = \"Run program\";document.getElementById(\"inputInUse14\").value = \"N\";<\/script>\n<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A list is a sequence of several variables, grouped together under a single name. Instead of writing a program with many variables x0, x1, x2, \u2026 you can define a single variable x and access its members x[0], x[1], x[2], &hellip; <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/13-lists\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1689","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/1689"}],"collection":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/comments?post=1689"}],"version-history":[{"count":0,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/1689\/revisions"}],"wp:attachment":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/media?parent=1689"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}