liveBook · Manning

Enumerate

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

enumerate() is a Python built-in function that produces pairs of indexes and values while iterating an iterable.

enumerate() produces index-and-value pairs while iterating an iterable. By default, counting starts at 0; use start=1 when display positions should begin at 1. section 21.2.2 section 21.4

Numbering an empty board

>>> board = 'XX.O.O...' >>> list(enumerate(board)) [(0, 'X'), (1, 'X'), (2, '.'), (3, 'O'), (4, '.'), (5, 'O'), (6, '.'), (7, '.'), (8, '.')] >>> list(enumerate(board, start=1)) [(1, 'X'), (2, 'X'), (3, '.'), (4, 'O'), (5, '.'), (6, 'O'), (7, '.'), (8, '.'), (9, '.')] Unpack each pair directly in a loop: `for i, char in enumerate(board, start=1)`. A list comprehension then replaces empty cells with their numbered positions while preserving X and O. section 21.2.2

def format_board(board):
    """Format the board"""
 
    cells = [str(i) if c == '.' else c for i, c in enumerate(board, start=1)] #1
    bar = '-------------'
    cells_tmpl = '| {} | {} | {} |'
    return '\n'.join([
        bar,
        cells_tmpl.format(*cells[:3]), bar,                                   #2
        cells_tmpl.format(*cells[3:6]), bar,
        cells_tmpl.format(*cells[6:]), bar
    ])

See enumerate() used inside format_board() to create numbered cells for a printable grid. section 21.2.2

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines returned pairs, default and custom starts, laziness, unpacking, and equivalent loop and comprehension forms.
Examples
Demonstrates board strings, REPL enumeration, numbered cells, and a tested format_board() function.
What it assumes
Assumes familiarity with lists, strings, loops, comprehensions, and iterable values.
What you can do after
Apply it via Python to iterate values alongside positions and format indexed output.
How it connects
Connects enumerate() with iterables, list comprehensions, for loops, tuple unpacking, and list().

Also explained in

Compare how 3 books explain enumerate →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.