Week 3 - Section 1 - Data types and a bit of gaming
Chapter 4.3 - Modifying and summing a list
4.3 - Modifying and summing a list
So how can we add all the items in a list?
Copy the following code to Thonny and save it as sumlist:
# Add items of a list
my_list = [5,76,8,5,3,3,56,5,23]
# Initial Sum should be zero
list_total = 0
# Loop from 0 up to the number of elements
# in the array:
for i in range(len(my_list)):
# Add element 0, next 1, then 2, etc.
list_total += my_list[i]
# Print the result
print(list_total)
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 :
# Add items of a list
my_list = [5, 76, 8, 5, 3, 3, 56, 5, 23]
# Initial Sum should be zero
list_total = 0
# Loop through array, copying each item in the array into
# the Variable named item.
for item in my_list:
# Add each item
list_total += item
# Print the result
print(list_total)
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 81 and then calculate the sum of this list. You should find 3266
Steps
- create an empty list with any name (ex. new_list)
- with a for loop append numbers from 11 to 81 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.