Edexcel International Advanced Level Computer Science, point 8.2.4
Every data structure has six basic operations. You must be able to select and use them on lists (and arrays), dictionaries and other structures (8.1.2). (Check the PLS for the exact methods allowed.)
| Operation | Meaning |
|---|---|
| Create | Make the structure (empty, or with starting items) |
| Insert | Add a new item |
| Update | Change an existing item |
| Retrieve | Read an item |
| Delete | Remove an item |
| Traverse | Visit every item in turn |
Lists and one-dimensional arrays
# Create
items = [] # empty list
scores = [0] * 5 # fixed-size array of 5 zeros
names = ["Amy", "Raj", "Li"]
# Insert
names.append("Sam") # at the end
names.insert(1, "Zoe") # at index 1; others move along
# Update
names[0] = "Anna" # replace by index
# Retrieve
print(names[2]) # by index
print(names[-1]) # last item
print(names[1:3]) # a slice
print("Li" in names) # is it there?
print(names.index("Li")) # where is it? (error if missing)
# Delete
removed = names.pop() # remove the last, and return it
del names[0] # remove by index
names.remove("Li") # remove by value (first match)
# Traverse
for name in names: # items only
print(name)
for i in range(len(names)): # by index
print(i, names[i])
for i, name in enumerate(names): # index and item together
print(i, name)
insertanddeletein the middle shift the items after them.- Deleting while looping over the same list can skip items: loop over a copy (
for x in names[:]) or build a new list. - Arrays keep a fixed size, so you update items instead of inserting and deleting.
Two-dimensional lists (arrays)
# Create: 3 rows, 4 columns of 0
grid = [[0] * 4 for _ in range(3)]
# Update / insert a value
grid[1][2] = 5
# Retrieve
print(grid[1][2]) # 5
print(grid[1]) # the whole row [0, 0, 5, 0]
# Traverse every cell
for r in range(len(grid)):
for c in range(len(grid[r])):
print(grid[r][c], end=" ")
print()
Dictionaries
# Create
ages = {}
ages = {"Amy": 17, "Raj": 18}
# Insert (and update, with the same syntax)
ages["Sam"] = 16 # new key: insert
ages["Amy"] = 18 # existing key: update
# Retrieve
print(ages["Raj"]) # KeyError if missing
print(ages.get("Zed")) # None if missing
print(ages.get("Zed", 0)) # default 0
print("Amy" in ages) # does the key exist?
# Delete
del ages["Raj"]
removed = ages.pop("Sam") # remove and return
# ages.clear() would remove every pair (lists have clear() too)
# Traverse
for key in ages: # keys
print(key)
for key, value in ages.items(): # keys and values
print(key, value)
print(list(ages.values())) # just the values
A list inside a dictionary
A dictionary's values can be lists, so one key can hold many items:
classes = {"10A": ["Amy", "Raj"], "10B": ["Li"]}
classes["10B"].append("Sam") # add to one class's list
classes["10C"] = [] # a new, empty class
for form, members in classes.items(): # traverse the dictionary...
print(form, len(members), "students")
for name in members: # ...and each list inside it
print(" ", name)
Saving a dictionary with JSON
JSON stores structures as text in a standard format, so a dictionary (or list) can be saved to a file and loaded back exactly:
import json
settings = {"volume": 7, "theme": "dark", "levels": [1, 2, 3]}
text = json.dumps(settings) # dictionary -> JSON string
print(text) # {"volume": 7, "theme": "dark", "levels": [1, 2, 3]}
back = json.loads(text) # JSON string -> dictionary
print(back["theme"]) # dark
with open("settings.json", "w") as f: # save to a file
json.dump(settings, f)
with open("settings.json", "r") as f: # load it back
loaded = json.load(f)
print(loaded == settings) # True
Records (a list of records)
students = [
{"name": "Amy", "mark": 87},
{"name": "Raj", "mark": 92},
]
students.append({"name": "Sam", "mark": 75}) # insert a record
students[0]["mark"] = 90 # update a field
for s in students: # traverse
print(s["name"], s["mark"])
Tuples and sets
- Tuples are immutable: you can't insert, update or delete, only create (
t = (1, 2)), retrieve (t[0]) and traverse. - Sets (8.2.7):
add,remove/discard, membership, and traverse (no order, no index).
Common mistakes
- Index out of range (
IndexError): the last valid index islen(x) - 1. - Missing key (
KeyError): checkinor useget. - Changing a list while traversing it.
- Rows that share a reference in a 2D list built with
[[0]*3]*2. - Forgetting that
appendchanges the list in place and returnsNone.
Worked example
Task: a list holds shopping prices. Write code to: create it, insert a price, update the first, delete the second, retrieve the largest, and traverse to print the total.
prices = [2.50, 4.00, 1.25] # create
prices.append(3.75) # insert at the end
prices[0] = 2.75 # update
del prices[1] # delete (the 4.00)
print(max(prices)) # retrieve the largest -> 3.75
total = 0
for p in prices: # traverse
total = total + p
print(total) # 7.75
Trace: [2.5, 4.0, 1.25], then [2.5, 4.0, 1.25, 3.75], then [2.75, 4.0, 1.25, 3.75], then [2.75, 1.25, 3.75]. The total is .
Exam tip: use the correct method for the structure (append and pop for lists, [key] and del for dictionaries). Show that you know when an index or key might not exist, and check first or handle the error. Trace by writing out the structure after each operation.
Check yourself
Give the six basic operations on a data structure
Create, insert, update, retrieve, delete and traverse.
What is the difference between names.append("X") and names.insert(0, "X")?
append adds the item at the end. insert(0, ...) puts it at the start and shifts the other items along.
How can you avoid a KeyError when retrieving from a dictionary?
Check the key is there with "key in d", or use d.get(key, default).
How do you traverse a 2D list?
With a nested loop: the outer loop goes through the rows and the inner loop through the columns.