Skip to content

Module 8 · Python Data Structures — topic 9 of 22

Nested lists

Lists inside lists represent tables, grids and matrices. Learn to create them safely, read and update cells, loop over rows and columns, compute row and column totals, and transpose.

Beginner 12 min read·Lesson 112 of 306 in Python Programming

Learning objectives

  • Create and display nested lists
  • Read and update cells with two indexes
  • Compute row and column totals and transpose a matrix

Definition

Lists inside lists represent tables, grids and matrices. Learn to create them safely, read and update cells, loop over rows and columns, compute row and column totals, and transpose.

Introduction

A nested list is a list whose items are themselves lists. The most common use is a table: the outer list holds rows, and each inner list holds the values in that row. table[1][2] is the value in row 1, column 2.

Why it matters

Marks for several students across several subjects, seating plans, game boards and spreadsheet data all have rows and columns. Nested lists let you represent them directly and process them with nested loops.

Detailed explanation

Create nested lists with a literal or a comprehension: [[0] * cols for _ in range(rows)]. Never use [[0] * cols] * rows, which shares one row.

len(table) is the number of rows; len(table[0]) the number of columns, assuming all rows have the same length.

Loop over rows with for row in table and over cells with an inner for cell in row.

Row totals: [sum(row) for row in table]. Column totals: sum(row[c] for row in table) for each column c.

zip(*table) groups items by column; list(map(list, zip(*table))) transposes rows into columns.

Rows don’t have to be the same length (a jagged list), but most calculations assume they are, so check when the data comes from outside.

For large numeric tables, NumPy arrays (Module 16) are faster and offer built-in maths.

Syntax

Python
table = [
[82, 91, 78],
[67, 74, 59],
]
cell = table[row][col]
row_totals = [sum(r) for r in table]
columns = list(zip(*table))
  • Each inner list is a row.
  • Two indexes select a cell.
  • zip(*table) groups by column.

Code examples

Reading and updating cells

Python
table = [[82, 91, 78], [67, 74, 59]]
print(table[0])
print(table[1][2])
table[1][2] = 62
print(table)
print(len(table), len(table[0]))
Output
[82, 91, 78]
59
[[82, 91, 78], [67, 74, 62]]
2 3

Looping over a grid

Python
grid = [[1, 2, 3], [4, 5, 6]]
for row in grid:
print(" ".join(str(n) for n in row))
Output
1 2 3
4 5 6

More examples

A marks table

Python
subjects = ["Maths", "Physics", "Chemistry"]
students = ["Asha", "Ben", "Chen"]
marks = [
[82, 91, 78],
[67, 74, 59],
[95, 88, 92],
]
print(f"{'':<6}" + "".join(f"{s:>10}" for s in subjects) + f"{'Total':>8}")
for name, row in zip(students, marks):
print(f"{name:<6}" + "".join(f"{m:>10}" for m in row) + f"{sum(row):>8}")
averages = [round(sum(col) / len(col), 1) for col in zip(*marks)]
print(f"{'Avg':<6}" + "".join(f"{a:>10}" for a in averages))
transposed = [list(col) for col in zip(*marks)]
print(transposed[0])
Output
           Maths   Physics Chemistry   Total
Asha          82        91        78     251
Ben           67        74        59     200
Chen          95        88        92     275
Avg         81.3      84.3      76.3
[82, 67, 95]

Step-by-step explanation

  • Each row of marks belongs to one student; each column to one subject.
  • zip(students, marks) pairs each name with its row for printing, and sum(row) gives the row total.
  • zip(*marks) groups the marks by column so each subject’s average can be computed.
  • transposed[0] is the Maths column as a list.

Expected output

Running “A marks table” prints exactly:

TextOutput
Maths Physics Chemistry Total
Asha 82 91 78 251
Ben 67 74 59 200
Chen 95 88 92 275
Avg 81.3 84.3 76.3
[82, 67, 95]

Practical applications

  • Exam systems store marks as rows of students and columns of subjects.
  • Image libraries treat images as grids of pixel values.
  • Board games such as chess and tic-tac-toe use 2D grids.

Best practices

  • Create grids with comprehensions.
  • Keep rows the same length, or validate it.
  • Use zip(*table) for column-wise work.

Common mistakes

Shared rows

Avoid

board = [["."] * 3] * 3

Prefer

board = [["."] * 3 for _ in range(3)]

With *, all three rows are the same list object.

Swapping row and column indexes

Avoid

table[col][row]

Prefer

table[row][col]

The first index selects the row (inner list), the second the column.

Key takeaways

  • Nested lists represent rows and columns.
  • table[r][c] selects a cell.
  • zip(*table) gives columns and transposes a matrix.

Try it yourself

  1. 1
    Create a 4 × 4 multiplication table as a nested list and print it.
  2. 2
    Find the highest mark in each column of a marks table.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic