Chapter 5

Arrays

FREE One-Dimensional Arrays (Lists)
Article ยท 15 min
๐Ÿ“ Homework 12

So far, we've stored single values in variables. But what if you have a list of things โ€” all the scores for a test, or items in a shopping cart? That's where lists (one-dimensional arrays) come in!


๐Ÿ“ฆ Creating a List

Syntax:

list_name = [item1, item2, item3]

Examples:

# A list of numbers
scores = [85, 92, 78, 90, 88]

# A list of strings
fruits = ["apple", "banana", "cherry"]

# Mixed types (Python allows this)
mixed = ["hello", 42, True, 3.14]

# Empty list
empty = []
1
Practice 1
โœ๏ธ Try it yourself!
1 Code
Create a list called colours containing 4 of your favourite colours.
2 Code
Create a list of 5 exam scores (any numbers).

๐Ÿ” Accessing Elements โ€” Indexing

Syntax โ€” index starts at 0:

list[index]

Examples:

fruits = ["apple", "banana", "cherry", "date"]

print(fruits[0])    # apple   (first element)
print(fruits[2])    # cherry  (third element)
print(fruits[-1])   # date    (last element!)
print(fruits[-2])   # cherry  (second from end)
๐Ÿ’ก Negative Indexing: fruits[-1] is always the last element. Super handy!
2
Practice 2
โœ๏ธ Try it yourself!
1 Code
Given nums = [10, 20, 30, 40, 50], print the first, third, and last elements.
2 Code
What is the index of the last element in a list of length n?

โœ‚๏ธ Slicing โ€” Getting a Sub-List

Syntax:

list[start:end]    # from start to end-1
list[:end]         # from beginning to end-1
list[start:]       # from start to end
list[::step]       # every step-th element

Examples:

numbers = [10, 20, 30, 40, 50, 60]

print(numbers[1:4])     # [20, 30, 40]  (index 1 to 3)
print(numbers[:3])      # [10, 20, 30]  (first 3)
print(numbers[3:])      # [40, 50, 60]  (from index 3)
print(numbers[::2])     # [10, 30, 50]  (every other)
print(numbers[::-1])    # [60, 50, 40, 30, 20, 10]  (reversed)
3
Practice 3
โœ๏ธ Try it yourself!
1 Code
Given nums = [5, 10, 15, 20, 25, 30], extract the first 3 elements and the last 2 elements.
2 Code
Use slicing to get every third element from [1,2,3,4,5,6,7,8,9].

โœ๏ธ Changing & Adding Elements

tasks = ["study", "code", "sleep"]

# Change an element
tasks[1] = "practice Python"
print(tasks)            # ['study', 'practice Python', 'sleep']

# Add to the end
tasks.append("eat")
print(tasks)            # ['study', 'practice Python', 'sleep', 'eat']

# Insert at a position
tasks.insert(1, "review")
print(tasks)            # ['study', 'review', 'practice Python', 'sleep', 'eat']

# Remove by value
tasks.remove("sleep")
print(tasks)            # ['study', 'review', 'practice Python', 'eat']

# Remove by index
popped = tasks.pop(0)
print(popped)           # study
print(tasks)            # ['review', 'practice Python', 'eat']
4
Practice 4
โœ๏ธ Try it yourself!
1 Code
Create a list of 3 favourite foods. Add two more, remove one, and change one.

๐Ÿ”ข Useful List Operations

scores = [85, 92, 78, 90, 88]

print(len(scores))      # 5
print(max(scores))      # 92
print(min(scores))      # 78
print(sum(scores))      # 433
print(sum(scores) / len(scores))  # 86.6 (average)

# Check membership
print(90 in scores)     # True
print(100 in scores)    # False
5
Practice 5
โœ๏ธ Try it yourself!
1 Code
Find the highest, lowest, and average of [34, 56, 78, 12, 90, 45].
2 Code
Check if the number 50 is in the list above.

๐Ÿ”„ Looping Through a List

# Method 1: for-each (simplest)
for fruit in ["apple", "banana", "cherry"]:
    print(f"I love {fruit}")

# Method 2: with index (when you need position)
for i, fruit in enumerate(["apple", "banana", "cherry"]):
    print(f"Fruit {i+1}: {fruit}")

# Method 3: modifying elements
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
    numbers[i] = numbers[i] * 2
print(numbers)          # [2, 4, 6, 8, 10]
6
Practice 6
โœ๏ธ Try it yourself!
1 Code
Loop through a list of names and print each one with "Hello, [name]!".
2 Code
Given [2, 4, 6, 8, 10], use a loop to calculate the total and average.

๐Ÿงฎ Algorithms โ€” Find Max, Min, and Count

# Find the maximum value
scores = [45, 78, 92, 60, 55, 88, 72]
highest = scores[0]
for s in scores:
    if s > highest:
        highest = s
print(f"Highest: {highest}")  # 92

# Find the minimum
lowest = scores[0]
for s in scores:
    if s < lowest:
        lowest = s
print(f"Lowest: {lowest}")    # 45

# Count how many passed
passed = 0
for s in scores:
    if s >= 50:
        passed += 1
print(f"Passed: {passed}")    # 6
7
Practice 7
โœ๏ธ Try it yourself!
1 Code
Find the highest score in [23, 45, 67, 12, 89, 34] using a loop (without max()).
2 Code
Count how many numbers in [12, 7, 15, 9, 20, 3, 18] are greater than 10.
FREE Two-Dimensional Arrays (Nested Lists)
Article ยท 15 min
๐Ÿ“ Homework 12

Imagine a spreadsheet, a chessboard, or a seating chart. These are two-dimensional โ€” they have rows and columns. In Python, we use lists of lists (nested lists).


๐Ÿ“Š Creating a 2D List

Syntax:

grid = [
    [row0_col0, row0_col1, ...],
    [row1_col0, row1_col1, ...],
    ...
]

Example โ€” 3ร—3 grid:

board = [
    ["X", "O", " "],
    [" ", "X", "O"],
    ["O", " ", "X"]
]

Access: board[row][col]

print(board[0][0])   # X  (top-left)
print(board[1][1])   # X  (center)
print(board[0][2])   # ' ' (empty)
1
Practice 1
โœ๏ธ Try it yourself!
1 Code
Create a 3ร—2 grid representing a classroom (3 rows, 2 columns) with student names.
2 Code
Access the element in row 1, column 1. Change it to a new value.

๐Ÿ—๏ธ Building a Grid with Nested Loops

# Create a 3ร—3 multiplication table
table = []
for row in range(1, 4):
    row_data = []
    for col in range(1, 4):
        row_data.append(row * col)
    table.append(row_data)

print(table)  # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
2
Practice 2
โœ๏ธ Try it yourself!
1 Code
Create a 4ร—4 grid where each cell contains the row number.
2 Code
Create a 3ร—3 grid of zeros using nested loops.

๐Ÿ” Traversing a 2D List

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Method 1: for-each (read)
for row in matrix:
    for val in row:
        print(val, end=" ")
    print()
# 1 2 3
# 4 5 6
# 7 8 9

# Method 2: with indices (for modification)
for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        matrix[i][j] *= 2

print(matrix)  # [[2, 4, 6], [8, 10, 12], [14, 16, 18]]
3
Practice 3
โœ๏ธ Try it yourself!
1 Code
Print the 4ร—4 grid you created in Practice 2 in a nice grid format.
2 Code
Modify a 3ร—3 grid so every cell equals row ร— column.

๐Ÿงฎ Algorithms with 2D Arrays

# Sum of all elements
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
total = 0
for row in matrix:
    for val in row:
        total += val
print(f"Total: {total}")  # 45

# Sum of the main diagonal (top-left to bottom-right)
diag_total = 0
for i in range(len(matrix)):
    diag_total += matrix[i][i]
print(f"Diagonal: {diag_total}")  # 1 + 5 + 9 = 15

# Find the largest element
largest = matrix[0][0]
for row in matrix:
    for val in row:
        if val > largest:
            largest = val
print(f"Largest: {largest}")  # 9
4
Practice 4
โœ๏ธ Try it yourself!
1 Code
Calculate the sum of each row in a 3ร—3 matrix.
2 Code
Find the largest element in a 4ร—4 matrix.
3 Code
Transpose a 3ร—3 matrix (swap rows and columns).
FREE Linear Search
Article ยท 15 min
๐Ÿ“ Homework 9

Now that you understand arrays and loops, let's combine them to solve real problems! First up: linear search โ€” the simplest way to find an item in a list.


๐Ÿ” What is Linear Search?

What it does: Check each item one by one from start to end until you find what you're looking for.

Algorithm steps:

  1. Start at the first element
  2. Compare it with the target value
  3. If it matches, return the position (found!)
  4. If not, move to the next element
  5. If you reach the end without finding it, return -1 (not found)

Python implementation:

def linear_search(items, target):
    """Return the index of target, or -1 if not found."""
    for i in range(len(items)):
        if items[i] == target:
            return i    # Found! Return position
    return -1           # Not found

# Test it
scores = [45, 78, 92, 60, 55]
result = linear_search(scores, 60)
print(f"60 found at index {result}")  # 3

result = linear_search(scores, 99)
print(f"99 found at index {result}")  # -1
๐Ÿ”‘ Key Points: Linear search works on any list (sorted or not). It stops as soon as it finds the target. Worst case = check every item (n comparisons).
1
Practice 1
โœ๏ธ Try it yourself!
1 Code
Write a linear search that counts how many times a value appears (not just found/not found).
2 Code
Write a linear search that returns a list of all indices where the target appears.
FREE Bubble Sort
Article ยท 15 min
๐Ÿ“ Homework 12

The second essential algorithm: bubble sort โ€” putting items in order by repeatedly swapping adjacent elements.


๐Ÿซง What is Bubble Sort?

What it does: Repeatedly swap adjacent items if they're in the wrong order. Larger items "bubble up" to the end.

Algorithm steps (one pass):

  1. Compare the first and second elements
  2. If the first is bigger, swap them
  3. Compare the second and third, swap if needed
  4. Continue until you reach the end
  5. After one pass, the largest element is at the end
  6. Repeat for the remaining items

Python implementation:

def bubble_sort(items):
    n = len(items)
    for pass_num in range(n - 1):
        swapped = False
        for i in range(n - 1 - pass_num):
            if items[i] > items[i + 1]:
                # Swap them!
                items[i], items[i + 1] = items[i + 1], items[i]
                swapped = True
        # If no swaps, already sorted!
        if not swapped:
            break
    return items

numbers = [64, 34, 25, 12, 22, 11, 90]
print(f"Before: {numbers}")
bubble_sort(numbers)
print(f"After:  {numbers}")
๐Ÿซง Interactive Bubble Sort Visualizer
๐Ÿ”„ Pass 0 ๐Ÿ‘† Compare 0 ๐Ÿ”€ Swaps 0 Comparing Swapping Sorted
Press โ–ถ Play or โญ Step to start
1
Practice 1
โœ๏ธ Try it yourself!
1 Code
Trace bubble sort on [5, 2, 8, 1] โ€” write each pass on paper first, then verify with the visualizer above.
2 Code
Modify bubble sort to count and print how many swaps it makes.
3 Code
Write bubble sort to sort in descending order (largest to smallest).

๐Ÿ“Š Visual Trace: Bubble Sort on [64, 34, 25, 12]

PassComparisonsSwaps?List after
164>34, 64>25, 64>12Yes ร—3[34, 25, 12, 64]
234>25, 34>12Yes ร—2[25, 12, 34, 64]
325>12Yes[12, 25, 34, 64] โœ…
2
Practice 2
โœ๏ธ Try it yourself!
1 Code
Draw a trace table for bubble sort on [7, 2, 9, 1]. List the list after each pass.