Skip to content

Module 8 · Python Data Structures — topic 4 of 22

Indexing

Access and change list items by position, including negative indexes, nested indexes for lists of lists, IndexError, and finding the index of a value with index().

Beginner 10 min read·Lesson 107 of 306 in Python Programming

Learning objectives

  • Read and replace list items by index
  • Use negative and nested indexes
  • Find a value’s position with index()

Definition

Access and change list items by position, including negative indexes, nested indexes for lists of lists, IndexError, and finding the index of a value with index().

Introduction

List items are numbered from 0, just like string characters. items[0] is the first item and items[-1] the last. Unlike strings, lists are mutable, so you can also assign to an index to replace an item.

Why it matters

Indexes let you work with specific positions: the top score after sorting, the current player in a turn-based game, the cell at row 2, column 3 of a grid.

Detailed explanation

Valid indexes run from 0 to len(items) - 1, and from -1 to -len(items) counting backwards. Anything else raises IndexError: list index out of range.

items[i] = value replaces the item at position i; the list length doesn’t change.

For a list of lists, use two indexes: grid[row][col]. The first selects the inner list, the second the item within it.

items.index(value) returns the position of the first equal item, or raises ValueError if it isn’t present. Check with in first when absence is possible.

Looping with enumerate() gives positions without manual indexing.

Indexes must be integers. Using a float, even 2.0, raises TypeError.

Syntax

Python
first = items[0]
last = items[-1]
items[1] = new_value
cell = grid[row][col]
position = items.index(value)
  • Indexes start at 0.
  • Assignment replaces an item.
  • Two indexes reach into nested lists.

Code examples

Reading and replacing

Python
players = ["Asha", "Ben", "Chen"]
print(players[0], players[-1])
players[1] = "Bela"
print(players)
print(players.index("Chen"))
Output
Asha Chen
['Asha', 'Bela', 'Chen']
2

Errors

Python
players = ["Asha", "Ben"]
try:
players[2]
except IndexError as err:
print("IndexError:", err)
try:
players.index("Zoe")
except ValueError as err:
print("ValueError:", err)
Output
IndexError: list index out of range
ValueError: list.index(x): x not in list

More examples

A turn-based game and a grid

Python
players = ["Asha", "Ben", "Chen"]
turn = 0
for _ in range(5):
print("Turn:", players[turn])
turn = (turn + 1) % len(players)
board = [
["X", "O", "X"],
[" ", "X", "O"],
["O", " ", "X"],
]
print("Centre:", board[1][1])
board[1][0] = "O"
print("Row 2:", board[1])
print("Diagonal:", [board[i][i] for i in range(3)])
Output
Turn: Asha
Turn: Ben
Turn: Chen
Turn: Asha
Turn: Ben
Centre: X
Row 2: ['O', 'X', 'O']
Diagonal: ['X', 'X', 'X']

Step-by-step explanation

  • turn indexes the current player and wraps around with % len(players).
  • board[1][1] selects the middle row, then its middle cell.
  • Assigning board[1][0] replaces one cell of the grid.
  • board[i][i] for i in 0, 1, 2 reads the diagonal from top-left to bottom-right.

Expected output

Running “A turn-based game and a grid” prints exactly:

TextOutput
Turn: Asha
Turn: Ben
Turn: Chen
Turn: Asha
Turn: Ben
Centre: X
Row 2: ['O', 'X', 'O']
Diagonal: ['X', 'X', 'X']

Practical applications

  • Games track whose turn it is with an index into a list of players.
  • Spreadsheet-like programs address cells as grid[row][col].
  • Leaderboards read the top entry with ranking[0].

Best practices

  • Use negative indexes for items at the end.
  • Check membership before calling index().
  • Prefer enumerate() over manual index counters.

Common mistakes

Using the length as an index

Avoid

items[len(items)]

Prefer

items[-1]

The last valid index is len(items) - 1.

index() on a missing value

Avoid

pos = names.index(name)

Prefer

pos = names.index(name) if name in names else -1

index() raises ValueError when the value isn’t present.

Key takeaways

  • List indexes start at 0; -1 is the last item.
  • items[i] = x replaces an item.
  • grid[r][c] reaches into nested lists; index() finds a value’s position.

Try it yourself

  1. 1
    Swap the first and last items of a list using indexes.
  2. 2
    Print the second column of a 3 × 3 list of lists.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

13 questions cover the “Python Data Structures” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module