Instead of seven variables for a week of temperatures, use one list: values inside square brackets [ ], separated by commas.
temp_list = [35, 34, 27, 29, 31, 33, 35] print(temp_list[0]) print(temp_list[4]) print(temp_list) print(len(temp_list))
35 31 [35, 34, 27, 29, 31, 33, 35] 7
temp_list[4]. len() gives the number of values.Going through a list
Add the values with a for loop, then divide by how many there are to get the average:
temp_list = [35, 34, 27, 29, 31, 33, 35]
total = 0
for i in range(len(temp_list)):
total = total + temp_list[i]
print(total / len(temp_list))32.0
You can also put the list itself after in and take the values directly:
fruit_list = ["lime", "berry", "mango"]
for fruit in fruit_list:
print(fruit)lime berry mango
Practice
Print the value 33 from the list.
temp_list = [35, 34, 27, 29, 31, 33, 35] print(___)
Press Run to see the result. Add up page_list with a for loop, then print the average (57.0).
page_list = [44, 70, 26, 88, 53, 61] total = 0
Press Run to see the result. Create color_list with red, green and blue, then print each value with for color in color_list:.
Press Run to see the result. A student's marks in 5 subjects: 78, 92, 85, 64, 90. Print the highest mark, then the number of subjects.
Hint
Usemax() and len().marks = [78, 92, 85, 64, 90]
Press Run to see the result. Print the first mark in marks as First: 78, then the last one as Last: 90. Write the last position with len(marks) - 1 so the program works however many marks there are.
Hint
Five values sit at positions 0 to 4.marks = [78, 92, 85, 64, 90]
Press Run to see the result. Key points
- A list
[a, b, c]; first valuex[0]; number of valueslen(x). for i in range(len(x)):by position, orfor v in x:for the values directly.