Python / Lists and arrays

Lists

Store many values in one variable, pick them out by position, and add them up with a for loop. Baccalaureate

Instead of seven variables for a week of temperatures, use one list: values inside square brackets [ ], separated by commas.

Python
temp_list = [35, 34, 27, 29, 31, 33, 35]
print(temp_list[0])
print(temp_list[4])
print(temp_list)
print(len(temp_list))
Console
35
31
[35, 34, 27, 29, 31, 33, 35]
7
Positions start at 0: day five is 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:

Python
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))
Console
32.0

You can also put the list itself after in and take the values directly:

Python
fruit_list = ["lime", "berry", "mango"]
for fruit in fruit_list:
    print(fruit)
Console
lime
berry
mango

Practice

1Fill in the blankCurriculum practice

Print the value 33 from the list.

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
temp_list = [35, 34, 27, 29, 31, 33, 35]
print(___)
Console
Press Run to see the result.
2Edit the programCurriculum practice

Add up page_list with a for loop, then print the average (57.0).

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
page_list = [44, 70, 26, 88, 53, 61]
total = 0
Console
Press Run to see the result.
3Write the programCurriculum practice

Create color_list with red, green and blue, then print each value with for color in color_list:.

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Console
Press Run to see the result.
4Write the programExtra practice

A student's marks in 5 subjects: 78, 92, 85, 64, 90. Print the highest mark, then the number of subjects.

HintUse max() and len().
Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
marks = [78, 92, 85, 64, 90]
Console
Press Run to see the result.
5Write the programExtra practice

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.

HintFive values sit at positions 0 to 4.
Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
marks = [78, 92, 85, 64, 90]
Console
Press Run to see the result.

Key points

  • A list [a, b, c]; first value x[0]; number of values len(x).
  • for i in range(len(x)): by position, or for v in x: for the values directly.