What is a 2D list?
A 2D list is a list where each element is another list. You can think of it as a grid (rows × columns) for storing related data (e.g. students and their test scores).
Defining a 2D list
Each inner list is one row (a single record):
# Each inner list: [Name, Score on Test 1, Score on Test 2]
student_scores = [
["John", 88, 92],
["Emma", 95, 89],
["Alex", 76, 84]
]
print(student_scores)
Loop over rows to display each record neatly:
for record in student_scores:
print(record)
Access rows & cells
Use two indices: the first selects the row, the second selects the column within that row.
# Emma is row index 1; her first test score is column index 1
print("Emma's first test score:", student_scores[1][1])
Edit & insert rows
Update a single cell, then insert a new row:
# Update Alex's second score (row 2, column 2)
student_scores[2][2] = 86
# Insert a new student at the top
student_scores.insert(0, ["Priya", 91, 94])
# Append a new student at the end
student_scores.append(["Mateo", 83, 88])
for row in student_scores:
print(row)
Searching in a 2D list
Find a record by name (case-insensitive):
search_name = input("Enter a student's name: ").strip().lower()
found = False
for row in student_scores:
if row[0].lower() == search_name:
print("Record found:", row)
found = True
break
if not found:
print("No record found.")
Practice tasks
Task 1: Build a friends table
Create a 2D list of three friends: [name, age, hobby]. Print all rows, then print only the second friend.
Show answer
friends = [
["Liam", 25, "Cycling"],
["Olivia", 30, "Reading"],
["Noah", 28, "Cooking"]
]
print("All friends:")
for f in friends:
print(f)
print("\nSecond friend:", friends[1])
Task 2: Update a cell
Using your friends table, update the hobby of the first friend, then print the updated table.
Show answer
# Update first friend's hobby
friends[0][2] = "Hiking"
for f in friends:
print(f)
Task 3: Insert and append rows
Insert a new friend at the start and append one at the end. Print the full table.
Show answer
friends.insert(0, ["Ava", 27, "Gaming"])
friends.append(["Ethan", 26, "Photography"])
for f in friends:
print(f)
Task 4: Search by name
Ask the user for a name and display that row if it exists (case-insensitive).
Show answer
name = input("Search name: ").strip().lower()
found = False
for row in friends:
if row[0].lower() == name:
print("Found:", row)
found = True
break
if not found:
print("No match.")
Task 5: Column totals (extension)
Given a 2D list of sales [name, q1, q2, q3], calculate the total of q2 across all rows.
Show answer
sales = [
["Store A", 1200, 1500, 1700],
["Store B", 1000, 800, 1300],
["Store C", 1600, 1100, 900]
]
total_q2 = 0
for row in sales:
total_q2 += row[2-1] # q2 at index 1
print("Q2 total =", total_q2)