{"id":2489,"date":"2025-09-21T11:28:04","date_gmt":"2025-09-21T03:28:04","guid":{"rendered":"http:\/\/blue.yn.cn\/?p=2489"},"modified":"2025-12-11T14:39:46","modified_gmt":"2025-12-11T06:39:46","slug":"lists","status":"publish","type":"post","link":"http:\/\/blue.yn.cn\/?p=2489","title":{"rendered":"8. Lists"},"content":{"rendered":"<h3>A list is a sequence<\/h3>\n<p>Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in lists are call elements or sometimes items.<\/p>\n<p>There are several ways to create a new list; the simplest is to enclose the elements in square brackets (&quot;[&quot; and &quot;]&quot;):<\/p>\n<pre><code class=\"language-python\">[10, 20, 30, 40]\n[&#039;crunchy frog&#039;, &#039;ram bladder&#039;, &#039;lark vomit&#039;]<\/code><\/pre>\n<p>The first example is a list of four integers. The second is three strings. The elements of a list don't have to be the same type. The following list contains a string, a float, an integer, and (lo!) another list:<\/p>\n<pre><code class=\"language-python\">[&#039;spam&#039;, 2.0, 5, [10, 20]]<\/code><\/pre>\n<p>A list within another list is nested.<\/p>\n<p>A list that contains no elements is called an empty list; you can create one with empty brackets, <code>[]<\/code>.<\/p>\n<p>As you might expect, you can assign list values to variables:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; cheeses = [&#039;Cheddar&#039;, &#039;Edam&#039;, &#039;Gouda&#039;]\n>&gt;&gt; numbers = [17, 123]\n>&gt;&gt; empty = []\n>&gt;&gt; print(cheeses, numbers, empty)\n[&#039;Cheddar&#039;, &#039;Edam&#039;, &#039;Gouda&#039;] [17, 123] []<\/code><\/pre>\n<h3>Lists are mutable<\/h3>\n<p>The syntax for accessing the elements of a list is the same as for accessing the characters of a string: the bracket. The expression inside the brackets specifies the index. Remenber that the indices start at 0:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; print(cheeses[0])\nCheddar<\/code><\/pre>\n<p>Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list. When the bracket operate appears on the left side of an assignment, it identifies the element of the list that will be assigned.<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; numbers = [17, 123]\n>&gt;&gt; numbers[1] = 5\n>&gt;&gt; print(numbers)\n[17, 5]<\/code><\/pre>\n<p>The one-th element of <code>numbers<\/code>, which used to be 123, is now 5.<\/p>\n<p>You can think of a list as a relationship between indices and elements. This relationship is called a mapping, each index &quot;maps to&quot; one of the elements.<\/p>\n<p>list indices work the same way as string indices:<\/p>\n<ul>\n<li>\n<p>Any integer expression can be used as an index.<\/p>\n<\/li>\n<li>\n<p>If you try to read or write an element that does not exist, you get an <code>IndexError<\/code>.<\/p>\n<\/li>\n<li>\n<p>If an index has a negative value, it counts backward from the end of the list.<\/p>\n<\/li>\n<\/ul>\n<p>The <code>in<\/code> operator also works on lists.<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; cheeses = [&#039;Cheddar&#039;, &#039;Edam&#039;, &#039;Gouda&#039;]\n>&gt;&gt; &#039;Edam&#039; in cheeses\nTrue\n>&gt;&gt; &#039;Brie&#039; in cheeses\nFalse<\/code><\/pre>\n<h3>Traversing a list<\/h3>\n<p>The most common way to traverse the elements of a list is with a <code>for<\/code> loop. The syntax is the same as for string:<\/p>\n<pre><code class=\"language-python\">for cheese in cheeses:\n    print(cheese)<\/code><\/pre>\n<p>This works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to do that is to combine the functions <code>range<\/code> and <code>len<\/code>:<\/p>\n<pre><code class=\"language-python\">for i in range(len(numbers)):\n    numbers[i] = numbers[i] * 2<\/code><\/pre>\n<p>This loop traverses the list and updates each element. <code>len<\/code> returns the number of elements in the list. <code>range<\/code> returns a list of indices from 0 to n-1, where n is the length of the list. Each time through the loop, <code>i<\/code> gets the index of the element. The assignment statements in the body uses <code>i<\/code> to read the old value of the element and to assign the new value.<\/p>\n<p>A <code>for<\/code> loop over a empty list never executes the body:<\/p>\n<pre><code class=\"language-python\">for x in empty:\n    print(&#039;This never happens.&#039;)<\/code><\/pre>\n<p>Although a list can contain another list, the nested list counts as a single element. The length of this list is four:<\/p>\n<pre><code class=\"language-python\">[&#039;spam&#039;, 1, [&#039;Brie&#039;, &#039;Roquefort&#039;, &#039;Pol le Veq&#039;], [1, 2, 3]]<\/code><\/pre>\n<h3>List Operations<\/h3>\n<p>The <code>+<\/code> operator concatenates lists:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; a = [1, 2, 3]\n>&gt;&gt; b = [4, 5, 6]\n>&gt;&gt; c = a + b\n>&gt;&gt; print(c)\n[1, 2, 3, 4, 5, 6]<\/code><\/pre>\n<p>Similarly, the <code>*<\/code> operator repeats a list a given number of times:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; [0] * 4\n[0, 0, 0, 0]\n>&gt;&gt; [1, 2, 3] * 3\n[1, 2, 3, 1, 2, 3, 1, 2, 3]<\/code><\/pre>\n<p>The first example repeats four times. The second example repeats the list three times.<\/p>\n<h3>List slices<\/h3>\n<p>The slice operator also works on lists:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;, &#039;d&#039;, &#039;e&#039;, &#039;f&#039;]\n>&gt;&gt; t[1:3]\n[&#039;b&#039;, &#039;c&#039;]\n>&gt;&gt; t[:4]\n[&#039;a&#039;, &#039;b&#039;, &#039;c&#039;, &#039;d&#039;]\n>&gt;&gt; t[3:]\n[&#039;d&#039;, &#039;e&#039;, &#039;f&#039;]<\/code><\/pre>\n<p>If you omit the fist index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you omit both, the slice is a copy of the whole list.<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t[:]\n[&#039;a&#039;, &#039;b&#039;, &#039;c&#039;, &#039;d&#039;, &#039;e&#039;, &#039;f&#039;]<\/code><\/pre>\n<p>Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle, or mutilate lists.<\/p>\n<p>A slice operator on the left side of an assignment can update multiple elements:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;, &#039;d&#039;, &#039;e&#039;, &#039;f&#039;]\n>&gt;&gt; t[1:3] = [&#039;x&#039;, &#039;y&#039;]\n>&gt;&gt; print(t)\n[&#039;a&#039;, &#039;x&#039;, &#039;y&#039;, &#039;d&#039;, &#039;e&#039;, &#039;f&#039;]<\/code><\/pre>\n<h3>Lists methods<\/h3>\n<p>Python provides methods that operate on lists. For example, <code>append<\/code> adds a new element to the end of a list:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;]\n>&gt;&gt; t.append(&#039;d&#039;)\n>&gt;&gt; print(t)\n[&#039;a&#039;, &#039;b&#039;, &#039;c&#039;, &#039;d&#039;]<\/code><\/pre>\n<p><code>extend<\/code> takes a list as an argument and appends all of the elements:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t1 = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;]\n>&gt;&gt; t2 = [&#039;d&#039;, &#039;e&#039;]\n>&gt;&gt; t1.extend(t2)\n>&gt;&gt; print(t1)\n[&#039;a&#039;, &#039;b&#039;, &#039;c&#039;, &#039;d&#039;, &#039;e&#039;]<\/code><\/pre>\n<p>This example leaves <code>t2<\/code> unmodified.<\/p>\n<p><code>sort<\/code> arranges the elements of the list from low to high:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t = [&#039;d&#039;, &#039;c&#039;, &#039;e&#039;, &#039;b&#039;, &#039;a&#039;]\n>&gt;&gt; t.sort()\n>&gt;&gt; print(t)\n[&#039;a&#039;, &#039;b&#039;, &#039;c&#039;, &#039;d&#039;, &#039;e&#039;]<\/code><\/pre>\n<p>Most list methods are void; they modify the list and return <code>None<\/code>. If you accidentally wirt <code>t = t.sort()<\/code>, you will be disappointed with the result.<\/p>\n<h3>Deleting elements<\/h3>\n<p>There are several ways to delete elements from a list. If you know the index of the element you want, you can use <code>pop<\/code>:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;]\n>&gt;&gt; x = t.pop(1)\n>&gt;&gt; print(t)\n[&#039;a&#039;, &#039;c&#039;]\n>&gt;&gt; print(x)\nb<\/code><\/pre>\n<p><code>pop<\/code> modifies the list and returns the elements that was removed. If you don't provide an index, it deletets and returns the last element.<\/p>\n<p>If you don't need the removed value, you can use the <code>del<\/code> statement:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;]\n>&gt;&gt; del t[1]\n>&gt;&gt; print(t)\n[&#039;a&#039;, &#039;c&#039;]<\/code><\/pre>\n<p>If you know the element you want to remove (but not the index), you can use <code>remove<\/code>:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;]\n>&gt;&gt; t.remove(&#039;b&#039;)\n>&gt;&gt; print(t)\n[&#039;a&#039;, &#039;c&#039;]<\/code><\/pre>\n<p>The return value from <code>remove<\/code> is <code>None<\/code>.<\/p>\n<p>To remove more than one element, you can use <code>del<\/code> with a slice index:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;, &#039;d&#039;, &#039;e&#039;, &#039;f&#039;]\n>&gt;&gt; del t[1:5]\n>&gt;&gt; print(t)\n[&#039;a&#039;, &#039;f&#039;]<\/code><\/pre>\n<p>As usual, the slice selects all the elements up to , but not including, the second index.<\/p>\n<h3>Lists and functions<\/h3>\n<p>There are a number of built-in functions that can be used on lists that allow you to quickly look through a list without writing your own loops:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; nums = [3, 41, 12, 9, 74, 15]\n>&gt;&gt; print(len(nums))\n6\n>&gt;&gt; print(max(nums))\n74\n>&gt;&gt; print(min(nums))\n3\n>&gt;&gt; print(sum(nums))\n154\n>&gt;&gt; print(sum(nums)\/len(nums))\n25<\/code><\/pre>\n<p>The <code>sum()<\/code> function only works when the list elements are numbers. The other functions \uff08<code>max()<\/code>, <code>len()<\/code>, etc.) work with lists of strings and other types that can be comparable.<\/p>\n<p>We could rewrite an earlier program that computed the average of a list of numbers entered by the user using a list.<\/p>\n<p>First, the program to compute an average without a list:<\/p>\n<pre><code class=\"language-python\">total = 0\ncount = 0\nwhile (True):\n    inp = input(&#039;Enter a number: &#039;)\n    if inp == &#039;done&#039;: break\n    value = float(inp)\n    total = total + value\n    count = count + 1\n\naverage = total \/ count\nprint(&#039;Average:&#039;, average)<\/code><\/pre>\n<p>In this program, we have <code>count<\/code> and <code>total<\/code> variables to keep the number and running total of the user's numbers as we repeatedly prompt the user for a number.<\/p>\n<p>We could simply remember each number as the user entered it and use built-in functions to computer the sum and count at the end.<\/p>\n<pre><code class=\"language-python\">numlist = list()\nwhile (True):\n    inp = input(&#039;Enter a number: &#039;)\n    if inp == &#039;done&#039;: break\n    value = float(inp)\n    numlist.append(value)\n\naverage = sum(numlist) \/ len(numlist)\nprint(&#039;Average:&#039;, average)<\/code><\/pre>\n<p>We make an empty list before the loop starts, and then each time we have a number, we append it to the list. At the end of the program, we simply compute the sum of the numbers in the list and divide it by the count of the numbers in the list to come up with the average.<\/p>\n<h3>Lists and strings<\/h3>\n<p>A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use <code>list<\/code>:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; s = &#039;spam&#039;\n>&gt;&gt; t = list(s)\n>&gt;&gt; print(t)\n[&#039;s&#039;, &#039;p&#039;, &#039;a&#039;, &#039;m&#039;]<\/code><\/pre>\n<p>Because <code>list<\/code> is the name of a built-in function, you should avoid using it as a variable name. I also avoid the letter &quot;l&quot; because it looks too much like the number &quot;1&quot;. So that's I use &quot;t&quot;.<\/p>\n<p>The <code>list<\/code> function breaks a string into individual letters. If you want to break a string into words, you can use the <code>split<\/code> method:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; s = &#039;pining for the fjords&#039;\n>&gt;&gt; t = s.split()\n>&gt;&gt; print(t)\n[&#039;pining&#039;, &#039;for&#039;, &#039;the&#039;, &#039;fjords&#039;]\n>&gt;&gt; print(t[2])\nthe<\/code><\/pre>\n<p>Once you have used <code>split<\/code> to break the string into a list of words, you can use the index operator (square bracket) to look at a particular word in the list.<\/p>\n<p>You can call <code>split<\/code> with an optional argument called a delimiter that specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; s = &#039;spam-spam-spam&#039;\n>&gt;&gt; delimiter = &#039;-&#039;\n>&gt;&gt; s.split(delimiter)\n[&#039;spam&#039;, &#039;spam&#039;, &#039;spam&#039;]<\/code><\/pre>\n<p><code>join<\/code> is the inverse of <code>split<\/code>. It takes a list of strings and concatenates the elements. <code>join<\/code> is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t = [&#039;pining&#039;, &#039;for&#039;, &#039;the&#039;, &#039;fjords&#039;]\n>&gt;&gt; delimiter = &#039; &#039;\n>&gt;&gt; delimiter.join(t)\n&#039;pining for the fjords&#039;<\/code><\/pre>\n<p>In this case the delimiter is a space character, so <code>join<\/code> puts a space between words. To concatenate strings without spaces, you can use the empty string, &quot;&quot;, as a delimiter.<\/p>\n<h3>Parsing lines<\/h3>\n<p>Usually when we are reading a file we want to do something to the lines other than just printing the whole line. Often we want to find the &quot;interesting lines&quot; and then parse the line to find some intersting part of the line. What if we wanted to print out the day of the week from those lines that start with &quot;From&quot;?<\/p>\n<pre><code class=\"language-python\">From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008<\/code><\/pre>\n<p>The <code>split<\/code> method is very effective when faced with this kind of problem. We can write a small program that looks for lines where the line starts withe &quot;From&quot;, <code>split<\/code> those lines, and then print out the third word in the line:<\/p>\n<pre><code class=\"language-python\">fhand = open(&#039;mbox-short.txt&#039;)\nfor line in fhand:\n    line = line.rstrip()\n    if not line.startswith(&#039;From &#039;): continue\n    words = line.split()\n    print(words[2])<\/code><\/pre>\n<p>The program produces the following output:<\/p>\n<pre><code class=\"language-python\">Sat\nFri\nFri\nFri\n...<\/code><\/pre>\n<p>Later, we will learn increasingly sophisticated techniques for picking the lines to work on and how we pull those lines apart to find the exact bit of information we are looking for.<\/p>\n<h3>Objects and values<\/h3>\n<p>If we execute these assignment statements:<\/p>\n<pre><code class=\"language-python\">a = &#039;banana&#039;\nb = &#039;banana&#039;<\/code><\/pre>\n<p>We know that <code>a<\/code> and <code>b<\/code> both refer to a string, but we don't know whether they refer to the same string. There are two possible states:<\/p>\n<p><img decoding=\"async\" src=\"\/wp-content\/uploads\/2025\/09\/image-1758704506001.png\" alt=\"file\" \/><\/p>\n<p>Variables and Objects<br \/>\nIn one case, <code>a<\/code> and <code>b<\/code> refer to two different objects that have the same value. In the second case, they refer to the same object.<\/p>\n<p>To check whether two variables refer to the same object, you can use the <code>is<\/code> operator.<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; a = &#039;banana&#039;\n>&gt;&gt; b = &#039;banana&#039;\n>&gt;&gt; a is b\nTrue<\/code><\/pre>\n<p>In this example, Python only created one string object, and both <code>a<\/code> and <code>b<\/code> refer to it.<\/p>\n<p>But when you create two lists, you get two objects:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; a = [1, 2, 3]\n>&gt;&gt; b = [1, 2, 3]\n>&gt;&gt; a is b\nFalse<\/code><\/pre>\n<p>In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical<\/p>\n<p>Until now, we have bee using &quot;object&quot; and &quot;value&quot; interchangeably, but it is more precise to say that an object has a value. If you execute <code>a = [1,2,3]<\/code>, <code>a<\/code> refers to a list object whose value is a particular sequece of elements. If another list has the same elements, we would say it has the same value.<\/p>\n<h3>Aliasing<\/h3>\n<p>If <code>a<\/code> refers to an object and you assign <code>b = a<\/code>, then both variables refer to the same object:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; a = [1, 2, 3]\n>&gt;&gt; b = a\n>&gt;&gt; b is a\nTrue<\/code><\/pre>\n<p>The association of a variable with an object is called a reference. In this example, there are two references to the same object.<\/p>\n<p>An object with more than one reference has more than one name, so we say that the object is aliased.<\/p>\n<p>If the aliased object is mutable, changes made with one alias affect the other:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; b[0] = 17\n>&gt;&gt; print(a)\n[17, 2, 3]<\/code><\/pre>\n<p>Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when you are working with mutable objects.<\/p>\n<p>For immutable objects like strings, aliasing is not as much of a problem. In this example:<\/p>\n<pre><code class=\"language-python\">a = &#039;banana&#039;\nb = &#039;banana&#039;<\/code><\/pre>\n<p>It almost never makes a difference whether <code>a<\/code> and <code>b<\/code> refer to the same string or not.<\/p>\n<h3>List arguments<\/h3>\n<p>When you pass a list to a function, the function gets a reference to the list. If the function modifies a list parameter, the caller sees the change. For example, <code>delete_head<\/code> removes the first element from a list:<\/p>\n<pre><code class=\"language-python\">def delete_head(t):\n    del t[0]<\/code><\/pre>\n<p>Here's how it is used:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; letters = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;]\n>&gt;&gt; delete_head(letters)\n>&gt;&gt; print(letters)\n[&#039;b&#039;, &#039;c&#039;]<\/code><\/pre>\n<p>The parameter <code>t<\/code> and the variable <code>letters<\/code> are aliases for the same object.<\/p>\n<p>It is important to distinguish between operations that modify lists and operations that create new lists. For example, the <code>append<\/code> method modifies a list, but the <code>+<\/code> operator creats a new list:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; t1 = [1, 2]\n>&gt;&gt; t2 = t1.append(3)\n>&gt;&gt; print(t1)\n[1, 2, 3]\n>&gt;&gt; print(t2)\nNone\n\n>&gt;&gt; t3 = t1 + [3]\n>&gt;&gt; print(t3)\n[1, 2, 3]\n>&gt;&gt; t1 is t3\nFalse<\/code><\/pre>\n<p>This difference is important when you write functions that are supposed to modify lists. For example, this function does not delete the head of a list:<\/p>\n<pre><code class=\"language-python\">def bad_delete_head(t):\n    t = t[1:]              # WRONG!<\/code><\/pre>\n<p>The slice operator creats a new list and the assignment makes <code>t<\/code> refer to it, but none of that has any effect on the list that was passed as an argument.<\/p>\n<p>An alternative is to write a function that creates and returns a new list. For example, <code>tail<\/code> returns all but the first element of a list:<\/p>\n<pre><code class=\"language-python\">def tail(t):\n    return t[1:]<\/code><\/pre>\n<p>This function leaves the original list unmodified. Here's how it is used:<\/p>\n<pre><code class=\"language-python\">>&gt;&gt; letters = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;]\n>&gt;&gt; rest = tail(letters)\n>&gt;&gt; print(rest)\n[&#039;b&#039;, &#039;c&#039;]<\/code><\/pre>\n<p><strong>Exercise 1:<\/strong> Write a function called <code>chop<\/code> that takes a list and modifies it, removing the first and last elements, and returns <code>None<\/code>. Then write a function called <code>middle<\/code> that takes a list and returns a new list that contains all but the first and last elements.<\/p>\n<pre><code class=\"language-python\">def chop(t):\n    del t[0]\n    del t[-1]\nletters = [1,2,3,4,5]\nprint(chop(letters))\nprint(letters)\nNone\n[2, 3, 4]<\/code><\/pre>\n<pre><code class=\"language-python\">def middle(t):\n    return t[1:-1]\nletters = [1,2,3,4,5]\nprint(middle(letters))\nprint(letters)\n[2, 3, 4]\n[1, 2, 3, 4, 5]<\/code><\/pre>\n<h3>Debugging<\/h3>\n<p>Careless use of lists (and other mutable objects) can lead to long hours of debugging. Here are some common pitfalls and ways to avoid them:<\/p>\n<ol>\n<li>Don't forget that most list methods modify the argumet and return <code>None<\/code>. This is the opposite of the string methods, which return a new string and leave the original alone.<\/li>\n<\/ol>\n<p>If you are used to writing string code like this:<\/p>\n<pre><code class=\"language-python\">word = word.strip()<\/code><\/pre>\n<p>It is tempting to write list code like this:<\/p>\n<pre><code class=\"language-python\">t = t.sort()           # WRONG!<\/code><\/pre>\n<p>Because <code>sort<\/code> returns <code>None<\/code>, the next operation you perform with <code>t<\/code> is likely to fail.<\/p>\n<p>Before using list methods and operators, you should read the documentation carefully and then test them in interactive mode. The methods and operators that lists share with other sequence (like strings) are documented at:<\/p>\n<p><a href=\"https:\/\/docs.python.org\/library\/stdtypes.html#common-sequence-operations\">https:\/\/docs.python.org\/library\/stdtypes.html#common-sequence-operations<\/a><\/p>\n<p>The methods and operators that only apply to mutable sequences are documented at:<\/p>\n<p><a href=\"https:\/\/docs.python.org\/library\/stdtypes.html#mutable-sequence-types\">https:\/\/docs.python.org\/library\/stdtypes.html#mutable-sequence-types<\/a><\/p>\n<ol start=\"2\">\n<li>Pick an idiom and stick with it.<\/li>\n<\/ol>\n<p>Part of the problem with lists is that there are too many ways to do things. For example, to remove an element from a list, you can use <code>pop<\/code>, <code>remove<\/code>, <code>del<\/code>, or even a slice assignment.<\/p>\n<p>To add an element, you can use the <code>append<\/code> method or the <code>+<\/code> operator. But don't forget that these are right:<\/p>\n<pre><code class=\"language-python\">t.append(x)\nt = t + [x]<\/code><\/pre>\n<p>And these are wrong:<\/p>\n<pre><code class=\"language-python\">t.append([x])          # WRONG!\nt = t.append(x)        # WRONG!\nt + [x]                # WRONG!\nt = t + x              # WRONG!<\/code><\/pre>\n<p>Try out each of these examples in interactive mode to make sure you understand what they do. Notice that only the last one causes a runtime error; the other three are legal, but they do the wrong thing.<\/p>\n<ol start=\"3\">\n<li>Make copies to avoid aliasing.<\/li>\n<\/ol>\n<p>If you want to use a method like <code>sort<\/code> that modifies the argument, but you need to keep the original list as well, you can make a copy.<\/p>\n<pre><code class=\"language-python\">orig = t[:]\nt.sort()<\/code><\/pre>\n<p>In this example you could also use the built-in function <code>sorted<\/code>, which returns a new, sorted list and leaves the original alone. But in that case you should avoid using <code>sorted<\/code> as a variable name!<\/p>\n<ol start=\"4\">\n<li>Lists, <code>split<\/code>, and files<\/li>\n<\/ol>\n<p>When we read and parse files, opportunities to encounter input that crash our program so it is a good idea to revisit the guardian pattern when it comes to wrinting programs that read through a file and look for a &quot;needle in the haystack&quot;.<\/p>\n<p>Let's revisit our program that is looking for the day of the week on the from lines of our file:<\/p>\n<pre><code class=\"language-python\">From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008<\/code><\/pre>\n<p>Since we are breaking this line into words, we could dispense with the use of <code>startswith<\/code> and simply look at the first word of the line to determine if we are interested in the line at all. We can use <code>continue<\/code> to skip lines that don't have &quot;From&quot; as the fist word as follows:<\/p>\n<pre><code class=\"language-python\">fhand = open(&#039;mbox-short.txt&#039;)\nfor line in fhand:\n    words = line.split()\n    if words[0] != &#039;From&#039; : continue\n    print(words[2])<\/code><\/pre>\n<p>This looks much simple and we don't even need to do the <code>rstrip<\/code> to remove the newline at the end of the file. But is it better?<\/p>\n<pre><code class=\"language-python\">Sat\nTraceback (most recent call last):\n  File &quot;search8.py&quot;, line 5, in &lt;module&gt;\n    if words[0] != &#039;From&#039; : continue\nIndexError: list index out of range<\/code><\/pre>\n<p>It kind of works and we see the day from the first line (Sat), but then the program fails with a traceback error. What went wrong?  What messed-up data caused our elegant, clever, and very Pythonic program to fail?<\/p>\n<p>You could stare at it for a long time and puzzle through it or ask someone for help, but the quicker and smarter approach is to add a <code>print<\/code> statement. The best to add the print statement is right before the line where the program failed and print out the data that seems to be causing the failure.<\/p>\n<p>Now this approach may generate a lot of lines of output, but at least you will immediately have some clue as to the problem at hand. So we add a print of the variable <code>words<\/code> right before line five. We even add a prefix &quot;Debug:&quot; to the line so we can keep our regular output separate from our debug output.<\/p>\n<pre><code class=\"language-python\">for line in fhand:\n    words = line.split()\n    print(&#039;Debug:&#039;, words)\n    if words[0] != &#039;From&#039; : continue\n    print(words[2])<\/code><\/pre>\n<p>When we run the program, a lot of output scrolls off the screen but at the end, we see our debug output and the traceback so we know what happened just before the traceback.<\/p>\n<pre><code class=\"language-python\">Debug: [&#039;X-DSPAM-Confidence:&#039;, &#039;0.8475&#039;]\nDebug: [&#039;X-DSPAM-Probability:&#039;, &#039;0.0000&#039;]\nDebug: []\nTraceback (most recent call last):\n  File &quot;search9.py&quot;, line 6, in &lt;module&gt;\n    if words[0] != &#039;From&#039; : continue\nIndexError: list index out of range<\/code><\/pre>\n<p>Each debug line is printing the list of words which we get when we <code>split<\/code> the line into words. When the program fails, the list of words is empty <code>[]<\/code>. If we open the file in a text editor and look at the file, at that point it looks as follows:<\/p>\n<pre><code class=\"language-python\">X-DSPAM-Result: Innocent\nX-DSPAM-Processed: Sat Jan  5 09:14:16 2008\nX-DSPAM-Confidence: 0.8475\nX-DSPAM-Probability: 0.0000\n\nDetails: http:\/\/source.sakaiproject.org\/viewsvn\/?view=rev&amp;rev=39772<\/code><\/pre>\n<p>The error occurs when our program encouters a blank line! Of cause there are &quot;zero words&quot; on a blank line. Why didn't we think of that when we were writing the code? When the code looks for the first word (<code>word[0]<\/code>) to check to see if it matches &quot;From&quot;, we get an &quot;index out of range&quot; error.<\/p>\n<p>This of course is the perfect place to add some guardian code to avoid checking the first word if the first word is not there. There are many ways to protect this code; we will choose to check the number of words we have before we look at the first word:<\/p>\n<pre><code class=\"language-python\">fhand = open(&#039;mbox-short.txt&#039;)\nfor line in fhand:\n    words = line.split()\n    # print(&#039;Debug:&#039;, words)\n    if len(words) == 0 : continue\n    if words[0] != &#039;From&#039; : continue\n    print(words[2])<\/code><\/pre>\n<p>First we commented out the debug print statement instead of removing it, in case of modification fails and we need to debug again. Then we added a guardian statement that checks to see if we have zero words, and if so, we use <code>continue<\/code> to skip to the next line in the file.<\/p>\n<p>We can think of the two <code>continue<\/code> statements as helping us refine the set of lines which are &quot;interesting&quot; to us and which we want to process some more. A line which has no word is &quot;uninteresting&quot; to us so we skip to the next line. A line which does not have &quot;From&quot; as its first word is uninteresting to us so we skip it.<\/p>\n<p>The program as modified run successfully, so perhaps it is correct. Our guardian statement does make sure that the <code>word[0]<\/code> will never fail, but perhaps it is not enough. When we are programming, we must always be thinking, &quot;What might go wrong?&quot;<\/p>\n<p><strong>Exercise 2:<\/strong> Figure out which line of the above program is still not properly guarded. See if you can construct a text file which causes the program to fail and then modify the program so that the line is properly guarded and test it to make sure it handles your new text file.<\/p>\n<pre><code class=\"language-python\">fhand = open(&#039;mbox-short.txt&#039;)\nfor line in fhand:\n    words = line.split()\n    # print(&#039;Debug:&#039;, words)\n    if len(words) == 0 : continue\n    if words[0] != &#039;From&#039; : continue\n    if len(words) &lt; 3 : continue\n    print(words[2])<\/code><\/pre>\n<p><strong>exercise 3:<\/strong> Rewrite the guardian code in the above example without two <code>if<\/code> statements. Instead, use a compound logical expression using the <code>or<\/code> logical operator with a single <code>if<\/code> statement.<\/p>\n<pre><code class=\"language-python\">fhand = open(&#039;mbox-short.txt&#039;, encoding=&#039;utf-8&#039;)\nfor line in fhand:\n    words = line.split()\n    if len(words) == 0 or words[0] != &#039;From&#039;: continue\n    print(words[2])<\/code><\/pre>\n<h3>Glossary<\/h3>\n<p><strong>aliasing<\/strong><br \/>\nA circumstance where two or more variable refer to the same object.<\/p>\n<p><strong>delimiter<\/strong><br \/>\nA character or string used to indicate where a string should be split<\/p>\n<p><strong>element<\/strong><br \/>\nOne of the values in a list (or other sequence); also called items;<\/p>\n<p><strong>equivalent<\/strong><br \/>\nHaving the same value.<\/p>\n<p><strong>index<\/strong><br \/>\nAn integer value that indicates an element in a list.<\/p>\n<p><strong>identical<\/strong><br \/>\nBeing the same object (which implies equivalence)<\/p>\n<p><strong>list<\/strong><br \/>\nA sequence of values.<\/p>\n<p><strong>list traversal<\/strong><br \/>\nThe sequential accessing of each element in a list.<\/p>\n<p><strong>nested list<\/strong><br \/>\nA list that is an element of another list.<\/p>\n<p><strong>object<\/strong><br \/>\nSomething a variable can refer to. An object has a type and value.<\/p>\n<p><strong>reference<\/strong><br \/>\nThe association between a variable and its value.<\/p>\n<h3>Exercises<\/h3>\n<p><strong>Exercise 4: Find all unique words in a file<\/strong><\/p>\n<p>Shakespheare used over 20000 words in his works. But how would you determine that? How would you produce the list of all the words that Shakespheare used? Would you download all his work, read it and track all unique words by hand?<\/p>\n<p>Let's use Python to achieve that instead. List all unique words, sorted in alphabetical order, that are stored in a file <code>romeo.txt<\/code> containing a subset of Shakespheare's worke.<\/p>\n<p>To get started, download a copy of the file <a href=\"www.py4e.com\/code3\/romeo.txt\">www.py4e.com\/code3\/romeo.txt<\/a>. Create a list of unique words, which will contain the final result. Write a program to open the file <code>romeo.txt<\/code> and read it line by line. For each line, split the line into a list of words using the <code>split<\/code> function. For each word, check to see if the word is already in the list of unique words. If the word is not in the list of unique words, add it to the list. When the program completes, sort and print the list of unique words in alphabetical order.<\/p>\n<pre><code class=\"language-python\">fname = input(&#039;Enter file: &#039;)\nfhand = open(fname, encoding=&#039;utf-8&#039;)\nt = list()\nfor line in fhand:\n    words = line.split()\n    for word in words:\n        if word not in t:\n            t.append(word)\nt.sort()\nprint(t)\nEnter file: romeo.txt\n[&#039;Arise&#039;, &#039;But&#039;, &#039;It&#039;, &#039;Juliet&#039;, &#039;Who&#039;, &#039;already&#039;, &#039;and&#039;, &#039;breaks&#039;, &#039;east&#039;, &#039;envious&#039;, &#039;fair&#039;, &#039;grief&#039;, &#039;is&#039;, &#039;kill&#039;, &#039;light&#039;, &#039;moon&#039;, &#039;pale&#039;, &#039;sick&#039;, &#039;soft&#039;, &#039;sun&#039;, &#039;the&#039;, &#039;through&#039;, &#039;what&#039;, &#039;window&#039;, &#039;with&#039;, &#039;yonder&#039;]<\/code><\/pre>\n<p><strong>Exercise 5: Minimalist Email Client.<\/strong><\/p>\n<p>MBOX (mail box) is a popular file format to store and share a collection of emails. This was used by early email servers and desktop apps. Without getting into too many details, MBOX is a text file, which stores emails consecutively. Emails are separated by a special line which starts with <code>From<\/code> (notice the space). Importantly, lines starting with <code>From:<\/code> (notice the colon) describes the email itself and does not act as a separator. Imagine you wrote a minimalist email app, that lists the email of the senders in the user's inbox and counts the numbers of emails.<\/p>\n<p>Write a program to read through the mail box data and when you find line that starts with &quot;From&quot;, you will split the line into words using the <code>split<\/code> function. We are interested in who sent the message, which is the second word on the From line.<\/p>\n<pre><code class=\"language-python\">From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008<\/code><\/pre>\n<p>You will parse the From line and print out the second word for each From line, then you will also count the numbers of From (not From:) lines and print out a count at the end. This is a good sample output with a few lines removed:<\/p>\n<pre><code class=\"language-python\">Enter a file name: mbox-short.txt\nstephen.marquard@uct.ac.za\nlouis@media.berkeley.edu\nzqian@umich.edu\n\n[...some output removed...]\n\nray@media.berkeley.edu\ncwen@iupui.edu\ncwen@iupui.edu\ncwen@iupui.edu\nThere were 27 lines in the file with From as the first word<\/code><\/pre>\n<pre><code class=\"language-python\">fname = input(&#039;Enter a file name: &#039;)\nfhand = open(fname, encoding=&#039;utf-8&#039;)\ncount = 0\nfor line in fhand:\n    if not line.startswith(&#039;From &#039;): continue\n    count = count + 1\n    words = line.split()\n    print(words[1])\nprint(&#039;There were&#039;, count, &#039;lines in the file with From as the first word&#039;)<\/code><\/pre>\n<p><strong>Exercise 6:<\/strong><\/p>\n<p>Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the end when the user enters &quot;done&quot;. Write the program to store the numbers the user enters in a list and use the <code>max()<\/code> and <code>min()<\/code> functions to compute the maximum and minimum numbers after the loop completes.<\/p>\n<pre><code class=\"language-python\">Enter a number: 6\nEnter a number: 2\nEnter a number: 9\nEnter a number: 3\nEnter a number: 5\nEnter a number: done\nMaximum: 9.0\nMinimum: 2.0<\/code><\/pre>\n<pre><code class=\"language-python\">t = list()\nwhile True:\n    inp = input(&#039;Enter a number: &#039;)\n    if inp == &#039;done&#039;:\n        break\n    t.append(float(inp))\nprint(&#039;Maximum: &#039;, max(t))\nprint(&#039;Minimum: &#039;, min(t))<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>A list is a sequence Like a string, a list is a sequenc&#8230; &raquo; <a class=\"read-more-link\" href=\"http:\/\/blue.yn.cn\/?p=2489\">\u9605\u8bfb\u5168\u6587<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[24],"tags":[],"class_list":["post-2489","post","type-post","status-publish","format-standard","hentry","category-python"],"_links":{"self":[{"href":"http:\/\/blue.yn.cn\/index.php?rest_route=\/wp\/v2\/posts\/2489","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/blue.yn.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/blue.yn.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/blue.yn.cn\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/blue.yn.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2489"}],"version-history":[{"count":11,"href":"http:\/\/blue.yn.cn\/index.php?rest_route=\/wp\/v2\/posts\/2489\/revisions"}],"predecessor-version":[{"id":2628,"href":"http:\/\/blue.yn.cn\/index.php?rest_route=\/wp\/v2\/posts\/2489\/revisions\/2628"}],"wp:attachment":[{"href":"http:\/\/blue.yn.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2489"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/blue.yn.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2489"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/blue.yn.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2489"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}