Module 3 - Section 2 - Lists

3.2.4 - Summing a list

So, how can we add all the items in a list using the sum command? This is very easy, but lets think how we can we the same with our own code.

Copy the following code to Thonny and save it as sumlist:


Take a closer look to the command range(len(my_list)). What do you think it does?

We can change the code to the following. Copy and paste it again to Thonny and save it as sumlist2 :


Try to find the differences of the two previous codes.

As an exercise write a code to create a list of all integer numbers from 11 to 91 and then calculate the sum of this list. You should find 4131

Steps

  1. create an empty list with any name (ex. new_list)
  2. with a for loop append numbers from 11 to 91 to the list
  3. create a variable total to sum the numbers and initiate it to 0
  4. with a new for loop add all items of the list to total variable

The solution can be found here.