2.3 Data Structures
Definitions, purpose, and Python examples
List
Definition: A list is a collection that can store multiple values in order.
Purpose: To group related items together.
When used: When data needs to be ordered and changeable.
Python example:
Purpose: To group related items together.
When used: When data needs to be ordered and changeable.
Python example:
scores = [10, 15, 20]
scores.append(25)
print(scores)
Array
Definition: An array stores multiple values of the same data type.
Purpose: Efficient storage of numerical data.
When used: When working with large, fixed‑type datasets.
Python note: Python lists are commonly used, but arrays exist via libraries.
Python example:
Purpose: Efficient storage of numerical data.
When used: When working with large, fixed‑type datasets.
Python note: Python lists are commonly used, but arrays exist via libraries.
Python example:
from array import array
numbers = array('i', [1, 2, 3, 4])
numbers.append(5)
print(numbers)
Dictionary
Definition: A dictionary stores data as key–value pairs.
Purpose: Fast access to data using a key.
When used: When values must be labelled or looked up.
Python example:
Purpose: Fast access to data using a key.
When used: When values must be labelled or looked up.
Python example:
student = {
"name": "Alex",
"age": 18,
"grade": "B"
}
print(student["name"])
2.3.2 Interpreting code using data structures
Interpreting Code
Interpreting code means understanding what each instruction does.
Python example:
Python example:
prices = [5, 10, 15]
total = 0
for price in prices:
total += price
print(total)
This code loops through the list and calculates the total.
2.3.3–2.3.4 Developing and debugging using data structures
Developing Code
Developing code involves writing new logic using data structures.
Python example:
Python example:
names = ["Sam", "Lee", "Jordan"]
for name in names:
print("Hello", name)
Debugging Code
Debugging means finding and fixing errors in code.
Example with bug:
Example with bug:
numbers = [1, 2, 3]
print(numbers[3])
Issue: Index out of range.
Fix: Use a valid index (0–2).
2.4 Operators (used with data structures)
Using Operators with Data Structures
Operators are used to process data in structures.
Python example:
Python example:
numbers = [2, 4, 6]
result = numbers[0] + numbers[1]
print(result)
This uses the addition operator on list values.