Sign in

Intro to Computer Science

Unit 8

Lists and Data

5 topics · 21 practice questions · Free responseNot yet reviewed

Notes

Lists

  • A list like [4, 8, 15] is ordered and mutable. Indexes start at 0; -1 is the last item. Slices a[1:3] stop before the end index. Out-of-range indexes cause an IndexError.
  • Methods: append, insert, remove, pop. Functions: len, sum, min, max. Test membership with in.

Iteration, searching and sorting

  • Loop with for item in list or for 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 returns None. Selection sort and bubble sort are simple sorting ideas.

Dictionaries

  • A dictionary maps unique keys to values: {"Ana": 15}. Look up with d["Ana"], add with d["Cy"] = 14, and use d.get(key, default) to avoid a KeyError.
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

With lst = ["a", "b", "c", "d"], what does print(lst[-2]) display?
What does a = [1, 2, 3]; a.append(4); print(a[3]) display?
What does print(max([5, 12, 7]) - min([5, 12, 7])) display?
What does total = 0; for n in [1, 2, 3]: total += n * 2, then print(total), display?
With d = {"red": 3, "blue": 5}, what does print(d["red"] + d["blue"]) display?
Which approach finds an item in an unsorted list?

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: