Topic 05 of 12 | π Lecture 5 β ICT582Topic05.pdf
Data Structures
Lists, tuples, sets, and dictionaries β Python's built-in collection types.
π― Learning Objectives
- Create and manipulate lists: indexing, slicing, and built-in methods
- Explain the difference between lists (mutable) and tuples (immutable)
- Use sets for unique-element collections and set operations
- Create and use dictionaries: access, add, update, and iterate
- Iterate over each collection type using
forloops
π Key Concepts
Lists β Ordered, Mutable
Created with square brackets []. Items can be any type and can be changed.
fruits = ["apple", "banana", "cherry"]
nums = [10, 20, 30, 40, 50]
# Indexing (starts at 0)
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last element)
# Slicing [start:stop] β stop is exclusive
print(nums[1:4]) # [20, 30, 40]
print(nums[:3]) # [10, 20, 30]
print(nums[::2]) # [10, 30, 50] (every 2nd)
List Methods
| Method | What it does |
|---|---|
L.append(x) | Add x to end |
L.extend([a,b]) | Add all items from another list |
L.insert(i, x) | Insert x at index i |
L.remove(x) | Remove first occurrence of x |
L.pop(i) | Remove & return item at index i (default: last) |
L.sort() | Sort in place (ascending) |
L.reverse() | Reverse in place |
L.index(x) | Return index of first x |
L.count(x) | Count occurrences of x |
len(L) | Number of elements |
L = [3, 1, 4, 1, 5]
L.append(9) # [3, 1, 4, 1, 5, 9]
L.sort() # [1, 1, 3, 4, 5, 9]
L.pop() # removes 9; L = [1, 1, 3, 4, 5]
print(len(L)) # 5
Tuples β Ordered, Immutable
Created with round brackets (). Once created, items cannot be changed.
point = (3, 4)
colors = ("red", "green", "blue")
print(point[0]) # 3
print(colors[1]) # green
# Tuple unpacking
x, y = point
print(x, y) # 3 4
# Cannot modify:
point[0] = 10 # TypeError!
Use tuples for data that should not change (coordinates, RGB values, etc.).
Sets β Unordered, Unique Elements
Created with curly braces {}. Automatically removes duplicates. No indexing (unordered).
s = {3, 1, 4, 1, 5, 9, 2, 6, 5}
print(s) # {1, 2, 3, 4, 5, 6, 9} β no duplicates
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # Union: {1, 2, 3, 4, 5, 6}
print(A & B) # Intersection: {3, 4}
print(A - B) # Difference: {1, 2}
print(A ^ B) # Symmetric diff: {1, 2, 5, 6}
Set methods: s.add(x), s.remove(x), s.discard(x), len(s).
Dictionaries β Key-Value Pairs
Created with curly braces {key: value}. Keys must be unique. Access by key, not index.
student = {"name": "Alice", "age": 20, "gpa": 3.8}
# Access
print(student["name"]) # Alice
print(student.get("age")) # 20 (.get returns None if key missing)
# Add / update
student["city"] = "Perth" # adds new key
student["age"] = 21 # updates existing
# Delete
del student["city"]
# Iterate
for key, value in student.items():
print(key, ":", value)
Dictionary Methods
| Method | What it does |
|---|---|
d.keys() | Returns all keys |
d.values() | Returns all values |
d.items() | Returns (key, value) pairs |
d.get(key, default) | Returns value or default if key missing |
key in d | Check if key exists (True/False) |
Comparison: List vs Tuple vs Set vs Dict
| Type | Ordered | Mutable | Duplicates | Access by |
|---|---|---|---|---|
List [] | Yes | Yes | Yes | Index |
Tuple () | Yes | No | Yes | Index |
Set {} | No | Yes | No | Membership test |
Dict {k:v} | Yes* | Yes | Keys: No | Key |
*Dicts maintain insertion order in Python 3.7+
π» Code Examples
Example 1 β List operations
marks = [72, 85, 61, 90, 78]
marks.sort(reverse=True) # Sort descending
print("Top mark:", marks[0]) # 90
print("Average:", sum(marks) / len(marks)) # 77.2
Example 2 β Word frequency counter with dict
words = ["cat", "dog", "cat", "bird", "dog", "cat"]
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(freq) # {'cat': 3, 'dog': 2, 'bird': 1}
Example 3 β Remove duplicates with set
nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
unique = list(set(nums))
print(sorted(unique)) # [1, 2, 3, 4, 5, 6, 9]
β οΈ Exam Focus
- Know how list indexing and slicing works β
L[1:4]gives items at index 1, 2, 3. - Distinguish mutable (list, dict, set) vs immutable (tuple, str) β tuples cannot be changed after creation.
- Dictionary: access with
d[key]raises KeyError if missing; used.get(key)to avoid this. - Sets auto-remove duplicates β use when you need unique values.
- Know common list methods:
append,pop,sort,remove.
β Common Mistakes
- Trying to modify a tuple:
t[0] = 5raisesTypeError. - Confusing
L.sort()(in-place, returns None) withsorted(L)(returns new list). - Using
d[key]when key might not exist β used.get(key)or checkkey in dfirst. - Creating an empty set:
s = {}creates a dict! Uses = set().
β‘ Quick Recap
- List: ordered, mutable, allows duplicates β use
[]. - Tuple: ordered, immutable, allows duplicates β use
(). - Set: unordered, mutable, no duplicates β use
set()or{}(non-empty). - Dict: key-value pairs, keys unique β use
{key: value}. - Negative index:
L[-1]is the last element. - Slicing:
L[start:stop:step]β stop is exclusive.