{"id":309,"date":"2021-05-11T15:24:30","date_gmt":"2021-05-11T14:24:30","guid":{"rendered":"https:\/\/glennrowe.net\/programmingpages\/?p=309"},"modified":"2021-05-31T12:14:33","modified_gmt":"2021-05-31T11:14:33","slug":"lists-the-basics","status":"publish","type":"post","link":"https:\/\/glennrowe.net\/programmingpages\/2021\/05\/11\/lists-the-basics\/","title":{"rendered":"Lists: the basics"},"content":{"rendered":"<p>The Python <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">list<\/code> is a powerful data type with a lot of functionality, so we&#8217;ll cover it in several posts. Here we start with some of its basic properties.<\/p>\n<p>First, it&#8217;s important to understand that Python supports four different built-in compound data types: lists, tuples, sets and dictionaries. Each of these has its own set of rules and peculiarities.<\/p>\n<p>A list is an ordered, mutable collection of data elements. It allows duplicate elements, that is, you can have 2 or more elements of the same datum in a list.<\/p>\n<p>By\u00a0<em>ordered<\/em>, we mean that the items in a list are stored in a definite order, so that, if we access say the fourth element of the list, it will always be the same datum (unless we&#8217;ve modified the list in the meantime). It&#8217;s important to note that &#8216;ordered&#8217; does\u00a0<em>not<\/em> necessarily mean &#8216;sorted&#8217;, so, for example, numeric values in a list need not be in ascending order (although it is possible to sort the items in a list, but that&#8217;s a different operation, as we&#8217;ll see).<\/p>\n<p>By\u00a0<em>mutable<\/em>, we mean that the contents of a list can be changed, either by adding or removing elements, or by changing the data stored at an existing list position.<\/p>\n<p>As Python is a <a href=\"https:\/\/glennrowe.net\/programmingpages\/2021\/04\/30\/dynamic-typing\/\">dynamically typed<\/a> language, the elements in a list need not all be of the same data type, so we can mix ints, floats, strings and even other lists as elements within a given list.<\/p>\n<p>At this stage, it&#8217;s useful to play around with lists in the <a href=\"https:\/\/glennrowe.net\/programmingpages\/2021\/04\/21\/installing-visual-studio-for-python\/\">PowerShell<\/a>, so start one up and type &#8216;python&#8217; at the prompt to enter the Python interpreter.<\/p>\n<p>A list is specified by typing its elements, separated by commas, between square brackets. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x = [1,2,2,3,4,4,5]<\/pre>\n<p>If you now type <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x<\/code> at the prompt, you&#8217;ll just get <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">[1,2,2,3,4,4,5]<\/code> as the response.<\/p>\n<p>To access a particular element within a list, give the list&#8217;s name followed by the element&#8217;s position in square brackets. The elements of a list are indexed starting with 0 for the first item, so <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x[2]<\/code> gives the third element. Typing <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x[2]<\/code> after the above gives us 2.<\/p>\n<p>We can use the same notation to change a list element. Try typing <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x[2] = 'wibble'<\/code> followed by <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x<\/code>. You&#8217;ll see the list is now <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">[1, 2, 'wibble', 3, 4, 4, 5]<\/code>. This illustrates that you can mix data types within a list.<\/p>\n<p>Now try <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">y = [x, 3.14, -7+4j]<\/code>, and then type <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">y<\/code> to see what y looks like. You&#8217;ll see that it is <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">[[1, 2, 'wibble', 3, 4, 4, 5], 3.14, (-7+4j)]<\/code>. The list <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x<\/code> is now the first element of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">y<\/code>, followed by the float 3.14 and the complex number -7+4j.<\/p>\n<p>If you want a single list consisting of the elements of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x<\/code> followed by 3.14 and -7+4j, you can use the + operator: <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z = x + [3.14, -7+4j]<\/code>. If you print out <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z<\/code>, you&#8217;ll see that it is <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">[1, 2, 'wibble', 3, 4, 4, 5, 3.14, (-7+4j)].<\/code> Note that the inner pair of brackets around the first 7 elements is now absent, so all the primitive data elements are part of a single list. If you want to append a list to an existing list, you can use the += operator, as in <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x += [3.14, -7+4j]<\/code>.<\/p>\n<p>The number of elements in a list <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x<\/code> can be obtained using <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">len(x)<\/code>.<\/p>\n<h2>Exercises<\/h2>\n<p>1. Write a program that generates 10 random floats between 0 and 1 and stores them in a list. Given that, for a list x, the statement <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x.sort()<\/code> sorts the list into ascending order, print out both the original list and the sorted list. You&#8217;ll need the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">random()<\/code> function from the module <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">random<\/code> to generate the random numbers.<\/p>\n<span class=\"collapseomatic \" id=\"id69f34b66f2475\"  tabindex=\"0\" title=\"See answer\"    >See answer<\/span><span id='swap-id69f34b66f2475'  class='colomat-swap' style='display:none;'>Hide answer<\/span><div id=\"target-id69f34b66f2475\" class=\"collapseomatic_content \">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from random import *\r\nranList = []\r\nfor i in range(10):\r\n    ranList += [random()]\r\nprint('Unsorted list:')\r\nprint(ranList)\r\nranList.sort()\r\nprint('Sorted list:')\r\nprint(ranList)<\/pre>\n<\/div>\n<p>2. You&#8217;ll see from the above exercise that running the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">sort()<\/code> function on a list replaces the list with its sorted version. If you want to retain the original list as well as have a sorted version of the list, you&#8217;ll need to copy the list before you sort it. Investigate the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">copy()<\/code> function for a list, and modify the above program so that both the original list and its sorted version are present at the end (so you can print them both out <em>after<\/em> doing the sort).<\/p>\n<span class=\"collapseomatic \" id=\"id69f34b66f2550\"  tabindex=\"0\" title=\"See answer\"    >See answer<\/span><span id='swap-id69f34b66f2550'  class='colomat-swap' style='display:none;'>Hide answer<\/span><div id=\"target-id69f34b66f2550\" class=\"collapseomatic_content \">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from random import *\r\nranList = []\r\nfor i in range(10):\r\n    ranList += [random()]\r\nranCopy = ranList.copy()\r\nranList.sort()\r\nprint('Unsorted list:')\r\nprint(ranCopy)\r\nprint('Sorted list:')\r\nprint(ranList)\r\n<\/pre>\n<\/div>\n<h2>Accessing and changing list elements<\/h2>\n<p>As mentioned above, a single list element can be accessed or changed by specifying its index, as in <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x[2]<\/code>. We can also use a negative index to count backwards from the end of the list, so <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">x[-2]<\/code> is the second element from the end. When counting backwards, the last element of the list has index -1, the second last by -2 and so on. When counting forwards, the index starts at 0.<\/p>\n<p>We can also specify a range of indexes from within a list. The notation <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z[m:n]<\/code> returns a new list containing elements m&#8230;n-1 from the original list. With the list <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z = [1, 2, 'wibble', 3, 4, 4, 5, 3.14, (-7+4j)]<\/code>, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z[1:3]<\/code> is the list <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">[2, 'wibble']<\/code> (that is, the elements 1 and 2 from the original list). It&#8217;s often confusing that the index n in <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z[m:n]<\/code> is\u00a0<em>not<\/em> the index of the last element returned; rather it is the index of the element <em>after<\/em> the last element returned.<\/p>\n<p>This sublist notation has a couple of shorthand versions. The list <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z[:3]<\/code> returns elements 0 through 2, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z[3:]<\/code> returns elements 3 through to the end of the list, and <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z[:]<\/code> returns a\u00a0<em>copy<\/em> of the entire list (so this is an alternative to the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">copy()<\/code> function for copying a list).<\/p>\n<p>You can use negative indexes in sublist expressions, so that <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z[-3:-1]<\/code> returns sublist starting with the element third from the end and ending with the element\u00a0<em>just before<\/em> the last element (remember that the last element has index -1, and the sublist notation returns elements up to, but not including, the element with the second index).<\/p>\n<p>If you give an impossible combination of indexes, such as <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z[4:2]<\/code>, you just get back an empty list (rather than an error message, so be careful!). Also, if one of the indexes in a sublist is out of range (that is, no such element exists) you&#8217;ll still get a valid list returned, rather than an error. Specifying a\u00a0<em>single<\/em> list element that is out of range, however,\u00a0<em>will<\/em> give you an error. It can all be somewhat confusing, so just take care!<\/p>\n<p>A slice of a list can be modified using the colon notation. Consider the following:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList = []\r\nfor x in range(10):\r\n    xList += [x * x]\r\nprint(xList)\r\n\r\nxList[3:5] = ['a', 'b', 'c', 'd']\r\nprint(xList)\r\n\r\nxList[5:6] += [1.2, 2.4, 4.5]\r\nprint(xList)<\/pre>\n<p>The first print statement gives us a list of squares from 0 to 9: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]. The expression <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[3:5] = ['a', 'b', 'c', 'd']<\/code> replaces list elements 3 and 4 with [&#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217;, &#8216;d&#8217;], so <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList<\/code> is now [0, 1, 4, &#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217;, &#8216;d&#8217;, 25, 36, 49, 64, 81]. Note that when replacing a slice of a list with another list, the numbers of elements in the two lists need not be the same. In this example, we replaced 2 elements with 4 elements, so the new list expanded by 2 elements.<\/p>\n<p>We can use the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">+=<\/code> operator to add some elements to a location in the list, as the last example above shows. In this case the location 5 (currently the element &#8216;c&#8217;) has elements [1.2, 2.4, 4.5] added to it, so the new list is now [0, 1, 4, &#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217;, 1.2, 2.4, 4.5, &#8216;d&#8217;, 25, 36, 49, 64, 81].<\/p>\n<h2>Exercise<\/h2>\n<p>In the last example above, since we are adding elements to a particular location in the list, you might think we could replace <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[5:6] += [1.2, 2.4, 4.5]<\/code> with <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[5] += [1.2, 2.4, 4.5]<\/code>. Try it, and explain why it doesn&#8217;t work.<\/p>\n<span class=\"collapseomatic \" id=\"id69f34b66f259d\"  tabindex=\"0\" title=\"See answer\"    >See answer<\/span><span id='swap-id69f34b66f259d'  class='colomat-swap' style='display:none;'>Hide answer<\/span><div id=\"target-id69f34b66f259d\" class=\"collapseomatic_content \">\n<p>While <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[5:6]<\/code> refers to a slice of a list, the expression <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[5]<\/code> refers to a single element within the list, so its data type is whatever the data type of that element is. In this case, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[5]<\/code> is &#8216;c&#8217; (a string), so the expression <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[5] += [1.2, 2.4, 4.5]<\/code> attempts to concatenate a string with a list of floats, which isn&#8217;t a valid operation.<\/p>\n<\/div>\n<h2>The double colon operator<\/h2>\n<p>The single-colon version of list slicing discussed above has a more general form, in which we can specify not only the start and end points of the slice, but also the step size to be used when selecting elements in the slice. Consider the following:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList = []\r\nfor x in range(10):\r\n    xList += [x * x]\r\nprint(xList)\r\n\r\nprint(xList[2:6:2])\r\n\r\nprint(xList[-2:3:-1])\r\n\r\nprint(xList[-2:-3:-1])\r\n\r\nprint(xList[::-1])<\/pre>\n<p>We start with a list of squares from 0 to 9 as before, so <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList<\/code> starts as [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]. The expression <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[2:6:2]<\/code> starts at location 2 and ends at location 6-1=5, but proceeds in steps of 2, so elements 2 and 4 are selected. The resulting list is therefore [4, 16].<\/p>\n<p>The second example <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[-2:3:-1]<\/code> starts at location -2, which is the second element from the end, and proceeds to the element just before 3, in steps of -1. The slice therefore proceeds backwards, starting at element <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[8]<\/code>. The &#8216;element just before 3&#8217; in this context is the last element we encounter when counting <em>down<\/em> to 3, so it is element 4, which is <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[4]<\/code>, or 16. Thus <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[-2:3:-1]<\/code> gives us the list [64, 49, 36, 25, 16].<\/p>\n<p>The third example <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[-2:-3:-1]<\/code> again starts at the second-to-last element (element 8) and counts down in steps of 1, but ends at the element just before the third-to-last element (element 7). Thus this list contains only one element, which is <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[8]<\/code>, so we have [64].<\/p>\n<p>The last example <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[::-1]<\/code> contains only a step size of -1, meaning we step backwards through the list. When either the start or stop index is missing, the default value is to take the location that maximizes the portion of the list that is traversed. In this case, since neither start nor stop is specified, the entire list is processed, and, since we step backwards, this gives us the list in reverse order, so we have [81, 64, 49, 36, 25, 16, 9, 4, 1, 0].<\/p>\n<h2>Exercise<\/h2>\n<p>Predict (without running the code) what each print statement will print in the following code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">xList = []\r\nfor x in range(10):\r\n    xList += [x * x]\r\nprint(xList)\r\n\r\nprint(xList[5::-1])\r\n\r\nprint(xList[:5:-1])\r\n\r\nprint(xList[2:2:1])\r\n\r\nprint(xList[-2:2:1])\r\n\r\nprint(xList[-8:-3:2])\r\n\r\nprint(xList[::1])<\/pre>\n<span class=\"collapseomatic \" id=\"id69f34b66f25e0\"  tabindex=\"0\" title=\"See answer\"    >See answer<\/span><span id='swap-id69f34b66f25e0'  class='colomat-swap' style='display:none;'>Hide answer<\/span><div id=\"target-id69f34b66f25e0\" class=\"collapseomatic_content \">\n<p>The first print just gives us our list of squares: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81].<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[5::-1]<\/code> starts at <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[5]<\/code> and steps backwards in steps of 1. Since no stop index is given, the slice goes to the beginning of the list, so we have [25, 16, 9, 4, 1, 0].<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[:5:-1]<\/code> has an end index of 5, and a backwards step of size 1. Since no start index is given and we are stepping backwards through the list, we start at the end of the list and proceed down to the last element\u00a0<em>before<\/em> element 5, which is <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[6]<\/code>. The list is therefore [81, 64, 49, 36].<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[2:2:1]<\/code> starts at <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[2]<\/code> and proceeds forward in steps of 1. However, the end index is 2, which means that the slice ends at the element just\u00a0<em>before<\/em> <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[2]<\/code>, that is, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[1]<\/code>. Such a slice is impossible, so we get an empty list [].<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[-2:2:1]<\/code> starts at the second last element which is <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[8]<\/code> and steps forwards from there. The end point is given as index 2, which again cannot be reached by stepping forwards from element 8, so we again have an impossible slice and get an empty list [].<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[-8:-3:2]<\/code> starts at the eighth-to-last element <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[2]<\/code> and proceeds forwards in steps of 2 up to the third-to-last element <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[7]<\/code>, so we get [4, 16, 36].<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[::1]<\/code> steps forward in steps of 1. Since neither endpoint is specified, the entire list is processed, so we get the original list [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]. Thus <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList[::1]<\/code> is equivalent to a copy of\u00a0 <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList<\/code> .<\/p>\n<\/div>\n<p>One final note about list slices:\u00a0<strong>a list slice produces a new list containing the elements selected in the slice.<\/strong> In particular, the last example above xList[::1] produces a copy of the original xList. Consider:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xCopy = xList[::1]\r\nxCopy[3] = 'wibble'\r\nprint(xList, xCopy)<\/pre>\n<p>We would find that <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList<\/code> has not changed, but <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xCopy<\/code> is a modified version of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList<\/code>, so the two lists are now <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xList<\/code> ==\u00a0[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] and <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">xCopy<\/code> == [0, 1, 4, &#8216;wibble&#8217;, 16, 25, 36, 49, 64, 81].<\/p>\n<h2>Lists and for loops<\/h2>\n<p>A list can serve as a source of elements processed by a <a href=\"https:\/\/glennrowe.net\/programmingpages\/2021\/05\/10\/for-loops-and-the-range-function\/\">for loop<\/a>. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">z = [1, 2, 'wibble', 3, 4, 4, 5, 3.14, (-7+4j)]\r\nfor elem in z:\r\n    print(type(elem))<\/pre>\n<p>This program prints the data type of each element in the list, so we get<\/p>\n<p>&lt;class &#8216;int&#8217;&gt;<br \/>\n&lt;class &#8216;int&#8217;&gt;<br \/>\n&lt;class &#8216;str&#8217;&gt;<br \/>\n&lt;class &#8216;int&#8217;&gt;<br \/>\n&lt;class &#8216;int&#8217;&gt;<br \/>\n&lt;class &#8216;int&#8217;&gt;<br \/>\n&lt;class &#8216;int&#8217;&gt;<br \/>\n&lt;class &#8216;float&#8217;&gt;<br \/>\n&lt;class &#8216;complex&#8217;&gt;<\/p>\n<h2>Exercise<\/h2>\n<p>Write a program that asks the user for an integer <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">numRands<\/code>, then generates a list containing <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">numRands<\/code> random numbers between 0 and 1. You should sort this list (no need to retain a copy of the original list). You should then save the portion of the list with numbers &gt; 0.5 in a new list, print out the length of this list, and then calculate the average value of all the numbers in that list. If the random number generator is working properly, you&#8217;d expect the length of the sublist to be about half of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">numRands<\/code>, and the average value of numbers &gt; 0.5 to be around 0.75.<\/p>\n<p>There&#8217;s no need to check the user&#8217;s input is valid (although you can if you want to). You should include tests to handle the cases where either all the random numbers are &lt; 0.5 or &gt; 0.5.<\/p>\n<span class=\"collapseomatic \" id=\"id69f34b66f2622\"  tabindex=\"0\" title=\"See answer\"    >See answer<\/span><span id='swap-id69f34b66f2622'  class='colomat-swap' style='display:none;'>Hide answer<\/span><div id=\"target-id69f34b66f2622\" class=\"collapseomatic_content \">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from random import *\r\nwhile True:\r\n    numRands = input('How many random numbers (or \\'quit\\')? ')\r\n    if numRands == 'quit':\r\n        break\r\n\r\n    numRands = int(numRands)        # Number of random numbers to test\r\n    ranList = []\r\n    for i in range(numRands):       # Generate the list of randoms\r\n        ranList += [random()]\r\n    ranList.sort()                  # Sort it\r\n    count = 0\r\n    ranLength = len(ranList)\r\n    while count &lt; ranLength and ranList[count] &lt; 0.5:     # Find the first element &gt; 0.5\r\n        count += 1\r\n    upperHalf = ranList[count:]     # Create the sublist of elements &gt; 0.5\r\n    print('Number &gt; 0.5: ', len(upperHalf))\r\n    if len(upperHalf) &gt; 0:\r\n        average = 0.0\r\n        for num in upperHalf:           # Calculate the average of the sublist\r\n            average += num\r\n        average \/= len(upperHalf)\r\n        print('Average of upper half =', average)\r\n    else:\r\n        print('No elements &gt; 0.5')\r\n\r\n\r\n<\/pre>\n<p>Hopefully, the comments explain what the code is doing. The condition <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">count &lt; ranLength<\/code> on line 14 checks for the case where all random numbers are &lt; 0.5 (which can happen if <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">numRands<\/code> is small), and the test on line 18 checks for the case where all the numbers are &lt; 0.5 (so the sublist is empty), which again can happen if <code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">numRands<\/code> is small.<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>The Python list is a powerful data type with a lot of functionality, so we&#8217;ll cover it in several posts. Here we start with some of its basic properties. First, it&#8217;s important to understand that Python supports four different built-in compound data types: lists, tuples, sets and dictionaries. Each of these has its own set [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[],"class_list":["post-309","post","type-post","status-publish","format-standard","hentry","category-python","entry"],"_links":{"self":[{"href":"https:\/\/glennrowe.net\/programmingpages\/wp-json\/wp\/v2\/posts\/309","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/glennrowe.net\/programmingpages\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/glennrowe.net\/programmingpages\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/glennrowe.net\/programmingpages\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/glennrowe.net\/programmingpages\/wp-json\/wp\/v2\/comments?post=309"}],"version-history":[{"count":9,"href":"https:\/\/glennrowe.net\/programmingpages\/wp-json\/wp\/v2\/posts\/309\/revisions"}],"predecessor-version":[{"id":333,"href":"https:\/\/glennrowe.net\/programmingpages\/wp-json\/wp\/v2\/posts\/309\/revisions\/333"}],"wp:attachment":[{"href":"https:\/\/glennrowe.net\/programmingpages\/wp-json\/wp\/v2\/media?parent=309"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/glennrowe.net\/programmingpages\/wp-json\/wp\/v2\/categories?post=309"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/glennrowe.net\/programmingpages\/wp-json\/wp\/v2\/tags?post=309"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}