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!
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 = []
colours containing 4 of your favourite colours.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)
fruits[-1] is always the last element. Super handy!
nums = [10, 20, 30, 40, 50], print the first, third, and last elements.n?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)
nums = [5, 10, 15, 20, 25, 30], extract the first 3 elements and the last 2 elements.[1,2,3,4,5,6,7,8,9].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']
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
[34, 56, 78, 12, 90, 45].# 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]
[2, 4, 6, 8, 10], use a loop to calculate the total and average.# 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
[23, 45, 67, 12, 89, 34] using a loop (without max()).[12, 7, 15, 9, 20, 3, 18] are greater than 10.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).
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)
# 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]]
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]]
# 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
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 it does: Check each item one by one from start to end until you find what you're looking for.
Algorithm steps:
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
The second essential algorithm: bubble sort โ putting items in order by repeatedly swapping adjacent elements.
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):
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}")
| Pass | Comparisons | Swaps? | List after |
|---|---|---|---|
| 1 | 64>34, 64>25, 64>12 | Yes ร3 | [34, 25, 12, 64] |
| 2 | 34>25, 34>12 | Yes ร2 | [25, 12, 34, 64] |
| 3 | 25>12 | Yes | [12, 25, 34, 64] โ |