I. Creating Lists
We'll make three lists. One for the student names, and one each for the two exams.
students = ['Brooke', 'Coen', 'Blas', 'George']
exam1 = [85, 90, 80, 50]
exam2 = [ 95, 100, 100, 96]
Observe:
- Lists are delimited using square brackets:
[]
- Items in the list are separated by commas (
,
) - The
students
list is a list of four strings (words) delimited by quotation marks (you can use single or double quotation marks) - The exam lists are lists of numbers (hence the lack of quotation marks)
If we'd like to print out the whole list we can just write:
print(students)
['Brooke', 'Coen', 'Blas', 'George']
However, if we want to print out just one of the items in the list, we have to reference it by its index. Indexing starts with 0 so to get the first student's name we'd use:
print(students[0])
Brooke
Assignment
Write a program that prints out Blas' name and his grade for exam 1.
students = ['Brooke', 'Coen', 'Blas', 'George']
exam1 = [85, 90, 80, 50]
exam2 = [ 95, 100, 100, 96]
print(students[2], exam1[2])
Assignment
Make a list with the days of the week and use the list to have it print out:
Monday and Friday
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
print(days[1], "and", days[5])
Assignment
Make a list with the first 10 multiples of 2 (2, 4, 6...
), and have it print out the last number.
nums = [2, 4, 6, 9, 10, 12, 14, 16, 18, 20]
print(nums[-1])
nums[-1]
) used to index the last item in the list.
II. Referencing Items in a List
-
Forward Indexing:
- Starts at
0
for the first item. students[0]
--> 'Brooke'students[1]
--> 'Coen'
- Starts at
-
Backward Indexing (in python, but not all languages):
- The last item in the list has the index
-1
students[-1]
--> 'George'students[-2]
--> 'Blas'
- The last item in the list has the index
-
Slicing: To get a number of items from the sequence give the two indices separated by a colon (
:
):- The
students[1:3]
--> ['Coen', 'Blas']students[:2]
--> ['Brooke', 'Coen']students[1:]
--> ['Coen', 'Blas', 'George']- Notice that slicing gives the results as a shorter list.
students = ['Brooke', 'Coen', 'Blas', 'George']
print('students[0]:', students[0])
print('students[1]:', students[1])
print('students[-1]:', students[-1])
print('students[-2]:', students[-2])
print('students[1:3]:', students[1:3])
print('students[:2]:', students[:2])
print('students[1:]:', students[1:])
Outputs:
students[0]: Brooke
students[1]: Coen
students[-1]: George
students[-2]: Blas
students[1:3]: ['Coen', 'Blas']
students[:2]: ['Brooke', 'Coen']
students[1:]: ['Coen', 'Blas', 'George']
Assignment
Print the name of the second to last student using both forward and backward indexing :
Blas Blas
students = ['Brooke', 'Coen', 'Blas', 'George']
print( students[2], students[-2] )
Assignment
Print the Exam 1 grades of the last two students using slicing:
[80, 50]
exam1 = [85, 90, 80, 50]
print( exam1[2:] )
III. Looping (Iterating) Through Lists
You can quickly go through each item in a list using a for ... in ...
loop.
students = ['Brooke', 'Coen', 'Blas', 'George']
for s in students:
print( s, 'is a student')
In this case, the variable s
takes the value of each item in the list.
Outputs:
Brooke is a student
Coen is a student
Blas is a student
George is a student
It is sometimes necessary to get the index as well as the item while you go through the list, so you can reference parallel items in other lists.
Let's loop through the three lists and print out the total grade of each student (Exam 1 + Exam 2). We use the enumerate
function to get the index and the item simultaneously.
students = ['Brooke', 'Coen', 'Blas', 'George']
exam1 = [85, 90, 80, 50]
exam2 = [ 95, 100, 100, 96]
for i, s in enumerate(students):
total = exam1[i] + exam2[i]
print( i, s, total)
i
becomes the index, and s
is the value from the enumerated list.
Outputs:
0 Brooke 180
1 Coen 190
2 Blas 180
3 George 146
Assignment
Find, and print out, the student name and their average score from the two exams:
0 Brooke 90.0
1 Coen 95.0
2 Blas 90.0
3 George 73.0
students = ['Brooke', 'Coen', 'Blas', 'George']
exam1 = [85, 90, 80, 50]
exam2 = [ 95, 100, 100, 96]
for i, s in enumerate(students):
avg = (exam1[i] + exam2[i]) / 2
print( i, s, avg)
Assignment
For each of the students, print their name, grades on both exams, their total score, and their average score.:
index student Exam 1 Exam 2 Avg
0 Brooke 85 95 90.00
1 Coen 90 100 95.00
2 Blas 80 100 90.00
3 George 50 96 73.00
students = ['Brooke', 'Coen', 'Blas', 'George']
exam1 = [85, 90, 80, 50]
exam2 = [ 95, 100, 100, 96]
print( 'index, student, Exam 1, Exam 2, Average')
for i, s in enumerate(students):
avg = (exam1[i] + exam2[i]) / 2
print( i, s, exam1[i], exam2[i], avg)
students = ['Brooke', 'Coen', 'Blas', 'George']
exam1 = [85, 90, 80, 50]
exam2 = [ 95, 100, 100, 96]
print( f'{"index":^6} {"student":10} {"Exam 1":7} {"Exam 2":7} {"Avg":5}')
for i, s in enumerate(students):
avg = (exam1[i] + exam2[i]) / 2
print( f'{i:^6d} {s:10} {exam1[i]:^7} {exam2[i]:^7} {avg:.2f}')
IV. Creating Lists with Loops
Use for
loops to create numerical lists.
To create a list with the first 20 multiples of 3, we can first create an empty list (nums = []
) and then append
items using a loop.
nums = []
for i in range(20):
n = i * 3
nums.append(n)
print(nums)
Outputs:
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57]
You will have noticed that the output is not quite right, since it starts at zero instead of three. You can fix this either by changing the range function to range(1, 21)
or by changing the calculation of n to n = i * 3 + 3
Assignment
Make a list of the first 10 multiples of 5.
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
?
Assignment
Create two lists, one of the first 10 multiples of 4, and the second of the first 10 multiples of 7. Then use these two lists to create a new list of the products of the corresponding numbers from only the first five numbers of the two lists:
multiples of 4: [4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
multiples of 7: [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
products: [28, 112, 252, 448, 700]
nprods = []
for i in range(5):
n = n4s[i] * n7s[i]
nprods.append(n)
print("multiples of 4:", n4s)
print("multiples of 7:", n7s)
print("products:", nprods)