EthicsComputerCourses
Join training +91 90532 10052

Slicing & Nested Lists

Python · Lesson 32 of 240 Beginner 9 min read Updated

By the end of this lesson you will be able to cut any piece out of a list, replace or delete many items in one line, and store tables and grids as lists inside a list. You will also know why a copied table can still change behind your back.

You already met slicing on text in String Indexing & Slicing and the basic list methods in Lists. This lesson uses those rules on lists, then adds two things strings cannot do: changing a slice in place, and nesting.

Slicing a list

A slice is a piece of a list. You write items[start:stop:step], exactly as with strings. The slice starts at start, stops just before stop, and jumps by step. A slice is always a new list, so the original stays as it was.

Think of a week of sales at a tea stall in Jaipur, one number per day, Monday first.

PythonRun in editor
sales = [820, 640, 910, 700, 1250, 1680, 1420]   # Mon to Sun

print(sales[:3])       # Monday to Wednesday
print(sales[-2:])      # the weekend
print(sales[::2])      # every second day
print(sales[::-1])     # Sunday back to Monday
print(sales[2:100])    # past the end: no error
print(sales)           # unchanged
Output
[820, 640, 910]
[1680, 1420]
[820, 910, 1250, 1420]
[1420, 1680, 1250, 700, 910, 640, 820]
[910, 700, 1250, 1680, 1420]
[820, 640, 910, 700, 1250, 1680, 1420]

Every rule from strings carries over. Leaving out start means "from the beginning". Leaving out stop means "to the end". A negative step walks backwards. A slice that runs past the end simply stops there, while a single index like sales[7] raises IndexError.

Changing many items with slice assignment

Strings are immutable, but lists are mutable (changeable). So with a list, a slice can also appear on the left of =. This is called slice assignment: the items in the slice are replaced by the items on the right.

The clever part is that the new piece does not need the same length. The list grows or shrinks to fit. Picture a train with coaches: you can uncouple two coaches and attach three in their place.

PythonRun in editor
coaches = ["ENG", "S1", "S2", "S3", "B1", "GEN"]

coaches[1:3] = ["S1", "S2", "S3", "S4"]   # replace 2 coaches with 4
print(coaches)

coaches[5:5] = ["PANTRY"]                 # empty slice: insert at 5
print(coaches)

coaches[-1:] = []                          # replace the last coach with nothing
print(coaches)

del coaches[1:3]                           # delete a range
print(coaches)
Output
['ENG', 'S1', 'S2', 'S3', 'S4', 'S3', 'B1', 'GEN']
['ENG', 'S1', 'S2', 'S3', 'S4', 'PANTRY', 'S3', 'B1', 'GEN']
['ENG', 'S1', 'S2', 'S3', 'S4', 'PANTRY', 'S3', 'B1']
['ENG', 'S3', 'S4', 'PANTRY', 'S3', 'B1']

Step by step:

  1. coaches[1:3] covered "S1" and "S2". Four new coaches took their place, so the list grew by two.
  2. coaches[5:5] is an empty slice at position 5. Assigning to it inserts without removing anything.
  3. Assigning an empty list to a slice removes those items.
  4. del coaches[1:3] does the same job more clearly. It is the usual way to delete a range.

One rule is strict. When the slice has a step, such as [::2], Python needs exactly as many new items as the slice selects. Otherwise you get ValueError: attempt to assign sequence of size 2 to extended slice of size 3.

Lists inside lists

A list can hold any value, including other lists. A nested list (a list of lists) is the natural way to store a table: each inner list is one row. To read one cell, use two indexes: table[row][column].

Here are three students' marks in Maths, Science and English, from a school in Lucknow.

PythonRun in editor
marks = [
    [78, 85, 69],   # Aarav
    [92, 74, 88],   # Isha
    [65, 90, 71],   # Rohan
]

print(marks[1])        # Isha's whole row
print(marks[1][2])     # Isha's English mark
print(marks[-1][0])    # Rohan's Maths mark
print(len(marks), "rows,", len(marks[0]), "columns")
Output
[92, 74, 88]
88
65
3 rows, 3 columns

Read marks[1][2] from left to right. marks[1] gives the row [92, 74, 88]. Then [2] picks item 2 of that row. There is no special "2D" syntax; it is just two index steps.

Rows, columns and totals

To visit every cell, use a loop inside a loop: the outer loop takes each row, the inner loop takes each value in that row. Rows are easy to slice. Columns need a small loop or a comprehension, because a column is spread across all the rows.

PythonRun in editor
names = ["Aarav", "Isha", "Rohan"]
marks = [[78, 85, 69], [92, 74, 88], [65, 90, 71]]

for name, row in zip(names, marks):
    print(f"{name:<6} total {sum(row)}")

science = [row[1] for row in marks]
print("Science column:", science)
print("Best in Science:", max(science))

marks[2][0] = 68      # correct one cell
print(marks[2])
Output
Aarav  total 232
Isha   total 254
Rohan  total 226
Science column: [85, 74, 90]
Best in Science: 90
[68, 90, 71]

zip() pairs each name with its row (see for Loops). The comprehension [row[1] for row in marks] takes item 1 from every row, which builds the Science column. Changing one cell works like any assignment, with two indexes on the left.

Building a grid safely

To make an empty grid, build each row separately with a comprehension. The shortcut with * looks the same when printed, but it behaves very differently.

PythonRun in editor
good = [["-"] * 4 for _ in range(3)]
bad = [["-"] * 4] * 3

good[0][0] = "X"
bad[0][0] = "X"

print(good)
print(bad)
print(bad[0] is bad[1])
Output
[['X', '-', '-', '-'], ['-', '-', '-', '-'], ['-', '-', '-', '-']]
[['X', '-', '-', '-'], ['X', '-', '-', '-'], ['X', '-', '-', '-']]
True

[row] * 3 copies the reference to one row three times, so all three "rows" are the same list. The is operator confirms it: bad[0] and bad[1] are one object. The comprehension runs ["-"] * 4 three times and makes three separate rows. You will see exactly why this happens in Mutability, References & Copies.

Slices of nested lists are shallow

A slice copies the outer list only. The rows inside are shared between the original and the slice. This is called a shallow copy: one layer is new, the layers below are not.

PythonRun in editor
table = [["Pune", 31], ["Kochi", 29], ["Jaipur", 35]]

top_two = table[:2]
top_two.append(["Rohtak", 33])   # changes only the new outer list
top_two[0][1] = 32               # changes a shared row!

print(table)
print(top_two)
Output
[['Pune', 32], ['Kochi', 29], ['Jaipur', 35]]
[['Pune', 32], ['Kochi', 29], ['Rohtak', 33]]

Appending to top_two did not touch table, because the outer lists are different. But changing top_two[0][1] also changed table, because both outer lists hold the same ["Pune", ...] row. When you need fully separate rows, copy each row ([row[:] for row in table]) or use copy.deepcopy(), covered in the mutability lesson.

Putting it together: a cinema seat chart

A small cinema in Kochi has 3 rows of 6 seats. Let's build a seat chart and book some seats.

PythonRun in editor
# Step 1: build the grid, one separate list per row
seats = [["." for _ in range(6)] for _ in range(3)]

# Step 2: book single seats with two indexes
seats[0][2] = "B"
seats[0][3] = "B"

# Step 3: book four seats in row C at once with slice assignment
seats[2][1:5] = ["B"] * 4

# Step 4: print the chart with row letters
for letter, row in zip("ABC", seats):
    print(letter, " ".join(row))

# Step 5: count free seats
free = sum(row.count(".") for row in seats)
print("Free seats:", free)
Output
A . . B B . .
B . . . . . .
C . B B B B .
Free seats: 12

After Step 1 every seat shows .. Steps 2 and 3 mark booked seats with B; the slice [1:5] covers four seats, and four new values replace them. Step 4 joins each row into one line. Step 5 counts the dots row by row and adds the counts.

Common mistakes

  • Building a grid with [[0] * n] * m. Every row is the same list. Use [[0] * n for _ in range(m)].
  • Expecting a slice to deep-copy. table[:] makes a new outer list, but the rows are shared.
  • Mixing up the index order. grid[r][c] is row first, then column. grid[c][r] reads the wrong cell or raises IndexError.
  • Assigning the wrong number of items to a stepped slice. a[::2] = [...] needs exactly as many items as the slice selects.

Interview questions

1. What is the difference between a[1:3] = [9] and a[1] = [9]?

Slice assignment replaces the items at indexes 1 and 2 with the items of [9], so the list gets one item shorter. Index assignment replaces only item 1, and the new item is the list [9] itself, so you get a nested list.

2. Why does [[0] * 3] * 3 give a buggy grid?

The * operator repeats references, not objects. The outer list holds three references to one inner list, so a change made through any row appears in every row. A comprehension creates a new inner list on each pass.

3. Is table[:] a safe copy of a list of lists?

Only partly. It is a shallow copy: the outer list is new, but the inner lists are shared. Changing a row's contents through the copy changes the original. Use copy.deepcopy(table) or [row[:] for row in table] for independent rows.

4. How do you get one column from a list of rows?

Use a comprehension that picks the same index from every row, for example [row[2] for row in table]. There is no column slice for plain lists; libraries such as NumPy add that.

Key points

  • List slices follow the string rules: start, stop (excluded) and step; a slice returns a new list.
  • Slice assignment replaces a range, and the list grows or shrinks to fit; a[i:i] = [...] inserts.
  • del a[i:j] deletes a range; a stepped slice needs an exact number of new items.
  • A nested list stores a table; read a cell with table[row][column].
  • Build grids with a comprehension, never with [[x] * n] * m.
  • Slices are shallow copies: the inner lists are shared.

Exercise

A cricket coach in Rohtak records runs per ball, one list per over: overs = [[1, 0, 4, 1, 0, 2], [0, 0, 6, 1, 1, 4], [2, 1, 0, 0, 4, 6]]. Print the total runs of each over with its number. Print the runs of the last two overs combined, using a slice. The scorer made a mistake: in over 2 the last two balls were actually [1, 0, 0] because there was an extra ball. Fix it with slice assignment and print over 2 again. Finally print the best single ball score of the match.

Show solution
Python
overs = [[1, 0, 4, 1, 0, 2], [0, 0, 6, 1, 1, 4], [2, 1, 0, 0, 4, 6]]

for number, balls in enumerate(overs, start=1):
    print(f"Over {number}: {sum(balls)} runs")

last_two = overs[-2:]
print("Last two overs:", sum(sum(balls) for balls in last_two))

overs[1][-2:] = [1, 0, 0]
print("Over 2 now:", overs[1])

print("Best ball:", max(max(balls) for balls in overs))
Output
Over 1: 8 runs
Over 2: 12 runs
Over 3: 13 runs
Last two overs: 25
Over 2 now: [0, 0, 6, 1, 1, 0, 0]
Best ball: 6

overs[-2:] gives a new list holding the last two rows. overs[1][-2:] = [1, 0, 0] replaces two balls with three, so over 2 now has seven balls. The nested max() finds each over's best ball, then the best of those.

Quick Quiz

1. After a = [1, 2, 3, 4, 5] and a[1:4] = [0], what is a?

2. With grid = [[1, 2, 3], [4, 5, 6]], what is grid[1][0]?

3. Which line builds a 3 by 3 grid of zeros with separate rows?

4. With t = [[1], [2]] and c = t[:], what does c[0].append(9) do to t?

Learn Python with a mentor

Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call