What is a List?

A list holds items in order. A list in Python is enclosed in [ and ] and can have values separated by commas, like [1,2,3,4,5,6,7,8,9,10]. You probably use lists all the time. People often make a list before they go shopping or a list of things to do. A list has an order and each list item has a position in the list, like the first item in a list or the last item in a list.

a shopping list

Figure 2: A shopping list

When you ran the code in the last section, did you get 55? That’s the sum of all the numbers from 1 to 10. Here is the program again. Run it if you don’t remember what it printed before.

teacher note Teacher Note: Names are Just Words

Once you change the program above in order to use * instead of +, you will see that it is still using the name (variable) sum to represent the product of all the numbers in thingsToAdd. The program would be better if we used the right name for the variable: product instead of sum once we switched to multiplication (*) from addition (+). However, the program still works. In the end, the names for the variables are there for the benefit of the humans, not the computer. The computer doesn’t care if we name the program xyzzy1776. It will work with a bad variable name. It’s just not as readable. You should write your programs so that people can understand them, not just computers.

Using Better Variable Names

Let’s write that program again with a better variable name. We will use product instead of sum for the variable name that holds the result of the calculation. Step through the code below by clicking on the Forward button and note what value the variable number is set to each time through the loop. Also note how the variable product changes during the loop.

Activity: CodeLens 3 (Numbers_Product)

The following program calculates the average of a list of numbers, but the code is mixed up. First initialize the sum to 0. Then create the list of numbers. Loop through the list and each time add the current number to the sum. Print the sum divided by the number of items in the list. <b>Don’t forget that you must indent the lines that are repeated in the loop</b>.

You have attempted of activities on this page