In our programming, up until now, we were handicapped by the fact that we were able to handle only one item at a time, i.e. one sale or one book. Although, when using iteration, we were able to handle a number of books, the details of one book got lost once we started on the next one. We have now come to the point where we can at least partially solve this issue: lists.
Lists can be looked at as extensions of variables and, therefore, before looking at lists we shall revise what we have already learnt about variables. The main features of variables that we are familiar with include:
A variable is a small block of memory that is reserved to store one value.
A variable can store only one value at any one time.
If a new value is stored in a variable the previous value is lost and cannot be retrieved.
Within a program a variable is given a name. The name should describe what the data in the variable is used for.
We have mentioned those facts about variables in order to address many misconceptions learners have about them (Sorva, 2018) and as lists are extensions of variables we want to ensure that learners won't encounter lists, while having misconceptions about variables (Robins, 2019). For this reason we shall again take a look at the first program where we introduced variables.
Above we have some examples of the concept of list, at least as being used in Python programming. Firstly, like all variables, lists have names. Above our list have names: Distances, Attempts, Measures and NumOfPages.
Let us focus on the first list: Distances. Each item of the list are referred to as an element. Distances has eight elements 15, 215, 75, 128, 57, 84, 45 and 162. The other feature to note is that the elements start counting at zero and thus the list has eight elements.
To read any of the list's elements we need to use the name of the list and the index number of the element we want. Thus to get the third element and store it in a variable named dstnc we would a line of code like:
dstnc = Distances[2]
This would result in the value 75 being stored in the variable dstnc.
(Recall that the third element will have an index of 2 since the indexes start counting at zero.)
Now that we have some theoretical knowledge of the concept of lists it is time to begin our examination of the topic at a practical level. Listing 1 below contains a very simple example to start us off.
Our first lists program begins at line 2. A list variable lstNames is created. (Here we are following our CamelScript convention of using an abbreviation of the data typ as the first three letters of the variable's name.) This is followed by six text items separated by commas and enclosed in square brackets. The data being enclosed between square brackets indicates that the items between the same brackets are elements of a list
After the creation of the list at line 2, the rest of the program involves printing out three elements of the list: elements zero, 2 and 4. The program should therefore print out 'Tom', 'Harry' and 'Pat'.
Fig 3 shows a running of the program and we can see that it actually does print out 'Tom', 'Harry' and 'Pat'. To finish off this example the video below provides a notional machine to demonstrate the internal processing of Listing 1.
Listing 2 is similar to Listing 1. The main difference is that listing 2 uses a for loop to print out the entire contents of the list.
Here line 2 is exactly the same as in Listing 1. In line 3 a variable intListLength is created and the len() function is used to determine the length of the list lstNames. The length is then stored in the variable intListLength. In this case the value 6 is stored there.
Lines 4 and 5 comprise a for loop. As line 4 indicates, the loop will iterate up as far as the value stored in intListLength, which in our case is 6. Thus the counter, intListCounter will go through the values 0, 1, 2, 3, 4 and 5 and at each iteration will print out the appropriate element of the list.
In our two previous examples a list was already created for us. In this example, however we are given an empty list and we use data entered from the keyboard to populate the elements of the list. A while loop is used to control the data entry since we don't know how many data items the user will enter. Conversely a for loop is used to print the elements of the list, since by then we know how many elements the user entered.
At line 2 a blank list is created, by declaring a list variable lstName and assigning to it a blank list, denoted by the square brackets with nothing between them. This is a list waiting for data to be entered into it.
The input section of the program spans lines 3 - 6. It consists of a while loop. The priming read of the loop occurs at line 3 where the user is asked to enter a person's name. The loop proper begins at line 4 where the value entered by the user is tested for being blank. If it's not then the body of the loop is entered.
The loop's body starts at line 5, where the data entered by the user is appended to the list lstNames. The list now has one element in it and will be stored at position zero - remember the list indexes start counting at zero, not 1.
At line 6 the user is asked again to enter a person's name. Control then passes back to line 4 where once again the user's input is tested for being blank.
Once a blank value is received from the user the while loop is broken and control passes to line 7. Here the len() function is used to determine the length of the list and this value is then stored in the variable intLengthOfList. So now we know how long the list is, which means that we can use a for loop to print out it's contents!
Printing the contents of the list is done using the for loop that spans lines 8 and 9. It works exactly like the for loop in Listing 2.
Fig 5 shows a run through the program, where the user entered six names before breaking the loop by entering a blank. The blank is evidenced by the occurrence of "Enter a person's name:" without any input from the user.
There are no new concepts introduced here. However we have more data items to deal with and we look at multiple lists in order to handle those extra items.
The code above is an extension of Listing 1 from the page Expressions. In the Expressions example we were able to deal with one set of data items in order to process a sale, but to deal with a second sale we had to run the program a second time. Here, thanks to lists, we can deal with any number of sales.
Looking at lines 2 - 5 we see that the data items we are dealing with are:
Name
Price
Amount sold
Total
The technique we shall use will be to store the first set of items, i.e. name, price, amount and total in element zero of the lists lstNames, lstPrice, lstAmount and lstTotal. For the second set of data items they will be stored in element 1 in the same set of lists etc. So now, let us look at how we do that.
In lines 2 - 5 we create four blank lists, the first where the names will be stored etc.
Lines 6 - 15 is a while loop that controls the input and processing of the data. At line 6, which is the priming read of the loop, the user is asked to enter a name. At line 7 the while loop condition tests if the data entered was not a blank. If it was not then the body of the loop, i.e. lines 8 - 15 is entered. At lines 8 and 9 the price of an item and the amount purchased are entered and stored in the appropriately named variables. At line 10 the total is calculated by multiplying the amount purchased by the price and the result stored in floatTotal. This is very similar to the first example in Listing 1, but now we shall store our input and processed data in the lists. This is done at lines 11 - 14.
Here the person's name is appended to lstName, the price to lstPrice etc. If this is the first time through the loop, all of those variables will have their values stored in element zero of each list. If it is the second time through then the variables will have their values stored in element 1 of each of the lists etc.
Once the user enters a blank at line 15 the while loop is broken and control passes to line 16.
Here at line 16 the length of the lists, i.e. the number of customers and their details that were entered by the user is determined using the len() function and then stored in the variable intLengthOfList
Finally we come to the output part of our program, which in this case consists of the for loop that spans lines 17 - 21. Here the corresponding elements of each of the lists are printed as a group.
Lists allow us to store multiple values using the same name. We can expand any list, i.e. add extra data to them by using the append() function and we can search the list using the index of its elements. The indexing of a list begins at zero.
Collect the names of your favourite ten rock bands or singers and one album each for each band or singer. Now write a Python program that contains two lists:
A list for the names of the bands/singers
A list for the names of the albums
Ensure that the albums are in the same order in the albums list as the bands/singers are in their own list.
Now finish off the program by getting it to print out the name of each band/singer, along with their album.
A sample output would be:
Lady Gaga Fame Monster
Exercise 2
Modify Exercise 1 by adding another list containing the years that the albums were released. Also modify the output so that labels are used to explain the data. An example would be:
Lady Gaga released the album Fame Monster in the year 2009.
Exercise 3
Extend Exercise 2 so that the sales figures for each album is also include in another list. (Either make up your own sales figures or else check the album sales up on Wikipedia.) Assuming that an album costs $15 then modify the output so that as well as the previous items, it now also contains the revenue gained from the album's sales. An example output would be:
Lady Gaga released the album Fame Monster in the year 2009. It sold 1500000 copies thus earning $22500000
You are required to write a program that will collect details of a number of employees. For each employee the program will store each data item in an appropriately named variable. The data required to be entered are:
Employee Name
IRD Number
Department
Hourly Rate
Hours worked
Once data entry for each employee is complete the Gross Pay is calculated by multiplying Hourly Rate by Hours Worked. Once the value of Gross Pay is calculated, Tax is calculated. If Gross Pay is less than 500 then tax is calculated as 25% of the Gross Pay, otherwise it is calculated as 30% of the gross. Net Pay is calculated by subtracting Tax from Gross Pay. Both the data entered by the user and the calculated data must be appended to the appropriately named lists.
Once the data for an employee is saved to the lists the user is asked for the name of the next employee. This process continues until the user enters a blank for the employee's name. Once this occurs control is passed to the output section where the details of each employee are displayed with appropriate labels.