Book
Module 3 - Section 2 - Lists
Module 3 - Section 2 - Lists
Completion requirements
View
After the completion of this module the students will be able to:
- identify the various data types
- recognize lists
- create lists
- use the list methods
- use the random function
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
- create an empty list with any name (ex. new_list)
- with a for loop append numbers from 11 to 91 to the list
- create a variable total to sum the numbers and initiate it to 0
- with a new for loop add all items of the list to total variable
The solution can be found here.