Notes
Lists
- A list like
[4, 8, 15]is ordered and mutable. Indexes start at 0;-1is the last item. Slicesa[1:3]stop before the end index. Out-of-range indexes cause anIndexError. - Methods:
append,insert,remove,pop. Functions:len,sum,min,max. Test membership within.
Iteration, searching and sorting
- Loop with
for item in listorfor i in range(len(list))when the index is needed. - Linear search checks items one by one.
sorted(list)returns a new sorted list;list.sort()sorts in place and returnsNone. Selection sort and bubble sort are simple sorting ideas.
Dictionaries
- A dictionary maps unique keys to values:
{"Ana": 15}. Look up withd["Ana"], add withd["Cy"] = 14, and used.get(key, default)to avoid aKeyError.
data = [2, 9, 4]
biggest = data[0]
for n in data:
if n > biggest:
biggest = n
print(biggest)
This prints 9.
Topics in this unit
Each topic has its own short notes and practice.
Practice
lst = ["a", "b", "c", "d"], what does print(lst[-2]) display?Index -1 is d, so -2 is c.
a = [1, 2, 3]; a.append(4); print(a[3]) display?After appending, index 3 holds 4.
print(max([5, 12, 7]) - min([5, 12, 7])) display?12 - 5 = 7.
total = 0; for n in [1, 2, 3]: total += n * 2, then print(total), display?The loop adds 2, 4 and 6 to get 12.
d = {"red": 3, "blue": 5}, what does print(d["red"] + d["blue"]) display?3 + 5 = 8.
Binary search needs sorted data, so unsorted lists use linear search.
Free response
Write your answer first, then open the scoring guide.
Free-response question
A teacher stores quiz scores in the list scores = [80, 95, 70, 90].
(a) Write code that prints the first score and the last score.
Show the answer and scoring guide
print(scores[0])
print(scores[-1])
Check off the points you earned:
(b) Write a loop that counts how many scores are at least 85 and prints the count. State the output.
Show the answer and scoring guide
count = 0
for s in scores:
if s >= 85:
count += 1
print(count)
The output is 2 (95 and 90).
Check off the points you earned:
(c) The teacher stores each student's score in a dictionary: grades = {"Ana": 80}. Write one line to add "Ben" with a score of 92 and one line that prints Ana's score.
Show the answer and scoring guide
grades["Ben"] = 92
print(grades["Ana"])
Check off the points you earned: