Python Lists · Lesson 45 of 149

Python Copying and Nested Lists

What you will learn

  • The three ways to copy a list, and what shallow means for lists of lists
  • How to build a grid without the shared-row trap
  • How to read and change rows and columns
  • Transposing and flattening a nested list
  • Jagged lists and a real example: a board

This lesson builds on lesson 2.7 (references and copying). A short reminder: b = a gives a list two names, not a copy. A real copy is a new list.

1. Making copies

a = [1, 2, 3]
b = a.copy()
c = a[:]
d = list(a)
b.append(4)
print(a, b, c == a, d is a)
[1, 2, 3] [1, 2, 3, 4] True False

All three (a.copy(), a[:] and list(a)) make a new list with the same items. Changing the copy does not touch the original.

Quick check: after `b = a`, are `a` and `b` two lists?

No. They are one list with two names. Changing it through either name shows through the other.

2. Shallow copies share inner lists

For a list of numbers or text, that is all you need. But when the items are themselves lists, the copy has a new outer list and the same inner lists:

a = [[1, 2], [3, 4]]
b = a.copy()
b[0].append(9)
print(a)
print(a[0] is b[0], a is b)
[[1, 2, 9], [3, 4]]
True False

The outer lists are different (a is b is False) but both contain the same first inner list (a[0] is b[0] is True), so adding 9 through b shows up in a. This is called a shallow copy.

Notice the difference between changing inside an inner list and changing the outer list:

b.append([5, 6])
print(a)
print(b)
a[1] = ["new"]
print(b)
[[1, 2, 9], [3, 4]]
[[1, 2, 9], [3, 4], [5, 6]]
[[1, 2, 9], [3, 4], [5, 6]]

Adding to the outer list of b did not affect a, and replacing an item of a did not affect b. Only changes inside a shared inner list are visible to both.

Deep copies

For a copy that shares nothing, use copy.deepcopy:

import copy

a = [[1, 2], [3, 4]]
f = copy.deepcopy(a)
f[0].append(9)
print(a, f)
print(a[0] is f[0], a == [[1, 2], [3, 4]])
[[1, 2], [3, 4]] [[1, 2, 9], [3, 4]]
False True

deepcopy also handles lists nested to any depth, and dictionaries holding lists. For a plain grid, [row[:] for row in grid] is a quick hand-made deep copy of two levels.

3. Building a grid

A grid (or table, or matrix) is a list of rows, and each row is a list. The wrong way to build one is to repeat a row:

grid = [[0] * 3] * 2
grid[0][0] = 1
print(grid)
print(grid[0] is grid[1])
[[1, 0, 0], [1, 0, 0]]
True

* 2 repeated the same inner list twice, so both rows are one object. The right way makes a new row each time, with a list comprehension (chapter 12) or a loop:

good = [[0] * 3 for _ in range(2)]
good[0][0] = 1
print(good)
print(good[0] is good[1])
[[1, 0, 0], [0, 0, 0]]
False

([0] * 3 is safe, because the items 0 are numbers, which cannot change. Only repeating a mutable item is the problem.)

4. Reading and changing

Use two indexes: first the row, then the column:

m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(m[1], m[1][2], m[-1][-1], len(m), len(m[0]))
m[1][1] = 50
print(m)
[4, 5, 6] 6 9 3 3
[[1, 2, 3], [4, 50, 6], [7, 8, 9]]
  • m[1] is the whole second row.
  • m[1][2] is row 1, column 2.
  • len(m) is the number of rows, and len(m[0]) the length of the first row.

Row and column totals

print([sum(r) for r in m])
print([sum(col) for col in zip(*m)])
print(sum(sum(r) for r in m))
[6, 60, 24]
[12, 60, 18]
90

Row totals are easy. For columns, zip(*m) pairs up the first items of every row, then the second items, and so on (lesson 6.6).

5. Transposing

To transpose a grid is to swap its rows and columns. zip(*m) does it:

print([list(col) for col in zip(*m)])
[[1, 4, 7], [2, 50, 8], [3, 6, 9]]

The same result with explicit loops:

print([[row[i] for row in m] for i in range(3)])
[[1, 4, 7], [2, 50, 8], [3, 6, 9]]

6. Flattening

To flatten a list of lists into one list, use a comprehension with two for parts, or itertools.chain.from_iterable:

import itertools

print([x for r in m for x in r])
print(list(itertools.chain.from_iterable(m)))
[1, 2, 3, 4, 50, 6, 7, 8, 9]
[1, 2, 3, 4, 50, 6, 7, 8, 9]

The two for parts read in the same order as nested loops: for r in m first, then for x in r. You may see sum(m, []), which also works, but it is slow for long lists, so avoid it.

Any depth

When lists are nested to unknown depth, a function that calls itself (recursion, lesson 11.6) is the usual tool:

def flatten(x):
    out = []
    for item in x:
        if isinstance(item, list):
            out.extend(flatten(item))
        else:
            out.append(item)
    return out

print(flatten([1, [2, [3, [4]]]]))
[1, 2, 3, 4]

7. Jagged lists

Rows do not have to be the same length:

jagged = [[1], [2, 3], [4, 5, 6]]
print([len(r) for r in jagged])
print(max(jagged, key=len))
[1, 2, 3]
[4, 5, 6]

Be careful when you index by column, since a short row has no column 2.

8. Sharing on purpose, and by accident

The same inner list placed in two spots is one list:

x = [1, 2]
lst = [x, x]
x.append(3)
print(lst, lst[0] is lst[1])
[[1, 2, 3], [1, 2, 3]] True

If you wanted independent lists, copy them:

y = [1, 2]
lst2 = [y.copy(), y.copy()]
y.append(3)
print(lst2)
[[1, 2], [1, 2]]

The same care applies to a tuple holding a list: the tuple is fixed, but the list inside can still change (lesson 2.6):

t = ([1, 2], [3])
t[0].append(99)
print(t)
([1, 2, 99], [3])

Worked example: a tic-tac-toe board

Build a 3 by 3 board, place a mark in the middle, and print it.

board = [["." for _ in range(3)] for _ in range(3)]
board[1][1] = "X"
board[0][2] = "O"
for row in board:
    print(" ".join(row))

winner_row = all(cell == "X" for cell in board[1])
print(winner_row)
. . O
. X .
. . .
False
Step What it does
the nested comprehension makes 3 separate rows of 3 dots
board[1][1] = "X" row 1, column 1: the centre
" ".join(row) turns a row of single characters into text
all(...) on board[1] checks whether a whole row is X (it is not yet)

If the board had been built with [["."] * 3] * 3, placing the X would have filled the same square in every row.

Common mistakes

  • Building a grid with [[0] * 3] * 2. All rows are one list.
  • Using .copy() or [:] and then changing an inner list. It is shared; use copy.deepcopy.
  • Mixing up m[row][column]. The row comes first.
  • Indexing a column in a jagged list where a row is too short.
  • Using sum(m, []) to flatten big lists.
  • Forgetting that a tuple can hold a list that changes.

Key takeaways

  • .copy(), [:] and list() make shallow copies: the outer list is new, the inner lists are shared.
  • Use copy.deepcopy(x) for a fully independent copy.
  • Build grids with a new row each time: [[0] * 3 for _ in range(2)], never [[0] * 3] * 2.
  • m[row][column] reads a cell; zip(*m) gives the columns and the transpose.
  • Flatten with [x for r in m for x in r] or itertools.chain.from_iterable; use recursion for unknown depth.

Practice

1. After a = [[1], [2]] and b = a.copy(), then b[0].append(5), what is a?

Show answer

[[1, 5], [2]]. The copy is shallow, so both lists share the first inner list.

2. How do you make b an independent copy of a in question 1?

Show answer

import copy, then b = copy.deepcopy(a).

3. Write the correct way to make a table of 4 rows and 5 columns of zeros.

Show answer

table = [[0] * 5 for _ in range(4)].

4. What is m[2][0] for m = [[1, 2], [3, 4], [5, 6]]?

Show answer

5: row 2 is [5, 6], and column 0 is 5.

5. Flatten [[1, 2], [3], [4, 5]] into [1, 2, 3, 4, 5].

Show answer

[x for row in [[1, 2], [3], [4, 5]] for x in row].

6. Which expression gives the columns of m as tuples?

Show answer

list(zip(*m)).