Programming · Data Structures
up to +100 XP
Stop 2.3 · Programming · 3 min

Data Structures

Learn to organize and store data efficiently

Learning objectives:
  • Know list, array and dictionary, their purpose and when each is used (2.3.1)
  • Interpret, develop and debug code using data structures (2.3.2–2.3.4)

Data structures

A data structure stores a collection of values under one name so they can be accessed and processed together.

List

An ordered, changeable collection. Items are accessed by index, starting at 0, and can be of different types.

names = ["Ali", "Bea", "Cal"]
names.append("Dev")        # add to the end
names.insert(1, "Ana")     # insert at index 1
names.remove("Cal")        # remove a value
print(names[0], len(names))  # Ali 4

Use when you need a sequence that grows or shrinks, such as a queue of orders.

Array

An ordered collection where every item is the same data type. In Python you can use the array module. Because the type is fixed, arrays use memory efficiently.

import array
readings = array.array("i", [12, 15, 11])
readings.append(14)
print(readings[1])   # 15

Use when you store lots of values of one type, such as sensor readings.

Dictionary

A collection of key: value pairs. Each key is unique and is used to look up its value.

stock = {"pen": 40, "ruler": 12}
stock["pen"] = stock["pen"] - 1
print("ruler" in stock)   # True

Use when you need to find data by a meaningful label rather than a position.

Useful commands from Appendix 2

index(), append(), insert(), remove(), count(), pop(), sort(), in, not in, len().

Comparing them

StructureOrderedAccess byMixed typesBest for
ListYesIndexYesGeneral sequences
ArrayYesIndexNoMany values of one type
DictionaryBy insertionKeyYes (values)Looking things up by label

Common bugs

Quick check · 10 questions

Check what stuck.

+10 XP each
Question 1

Question 1 of 10

Which data structure stores key: value pairs?

Question 2

Question 2 of 10

Which data structure requires every item to be the same data type?

Question 3

Question 3 of 10

What does names = ["Ali", "Bea", "Cal"] then print(names[1]) output?

Question 4

Question 4 of 10

Which command adds an item to the end of a list?

Question 5

Question 5 of 10

You need to look up a product's price using its product code. Which structure is best?

Question 6

Question 6 of 10

What error happens if you look up a key that is not in a dictionary?

Question 7

Question 7 of 10

A list has 4 items. Why does items[4] fail?

Question 8

Question 8 of 10

What does len(["a", "b", "c"]) return?

Question 9

Question 9 of 10 · Match the pairs

Match each data structure to its description.

List
Array
Dictionary
Question 10

Question 10 of 10 · Coding

Write total(numbers) that returns the sum of a list of numbers without using sum().

Open the IDE
Hint

Loop through the list and add each number to running.