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.

    csp-7-3-1: Now, change the program above to get the product instead of the sum (e.g., replace + with *, and replace the 0 as the initial value of sum to 1). What do you get now when you run the program?
  • 55
  • That's the sum
  • 0
  • That's what you get if you leave the sum as 0. Multipying everything by 0 gets you 0
  • 3628800
  • That's 1*2*3*4*5*6*7*8*9*10
  • Error - number is too big
  • It should actually work

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.

(Numbers_Product)

    csp-7-3-2: What is the value of number the 3rd time through the loop?
  • 1
  • That's the value the first time through the loop
  • 2
  • That's the value the second time through the loop
  • 3
  • That's the value the third time through the loop
  • 4
  • That's the value the fourth time through the loop
  • 10
  • That's the value the last time through the loop
    csp-7-3-3: What is the value of product after the 4th time through the loop?
  • 6
  • That's the value after the 3rd time through the loop.
  • 10
  • That's the value if we were adding up the values rather than multiplying them.
  • 24
  • That's the value after the 4th time through the loop.
  • 120
  • That's the value after the 5th time through the loop.
        csp-7-3-4: 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.  Don't forget that you must indent the lines that are repeated in the loop.sum = 0
numbers = [90, 80, 75, 90, 83]
for number in numbers:
    sum = sum + number
print(sum / 5)
        

Define a function to calculate the sum of 1 to the passed number using the range function. Return the sum from the function. Call the function and print the result.

Show Comments

Note

Discuss topics in this section with classmates.

Show Comments
Next Section - The Range Function