Python Lists for Games

Python lists explained with games: a Tic Tac Toe board, an inventory, a snake's body. Indexing, slicing, append, insert, pop and list comprehensions.

A list holds many values in order. Games use lists for boards, inventories, high-score tables, enemies on screen, and even the snake in Snake.

example 1 · press Run, then edit and run again

Positions start at 0

The first item is [0]; the last is [-1]. A slice [a:b] takes items from a up to (not including) b, which is how Tic Tac Toe prints one row of its board.

example 2 · press Run, then edit and run again

insert() and pop(): how Snake moves

example 3 · press Run, then edit and run again

List comprehensions

Build a list in one line: [x * 2 for x in range(5)]. Add a condition to filter: [i for i in range(9) if board[i] == " "] lists the free squares.

💡 [["."] * 7] * 6 makes six references to the SAME row. Use [["."] * 7 for _ in range(6)] for a grid.

Games that use Lists

Practise this with 12 of the 20 games:

Frequently asked questions

How do I add an item to a list in Python?

append(x) adds to the end, insert(i, x) adds at position i. extend() adds several items.

What's the difference between remove() and pop()?

remove(x) deletes the first item equal to x. pop(i) deletes the item at position i (the last one if you give no position) and returns it.

More Python concepts