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.
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.
insert() and pop(): how Snake moves
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:
- #01☆☆☆
Tic Tac Toe in Python
Learn Lists, Functions and if, elif and else.
- #03☆☆☆
Snake Game in Python (Turtle)
Learn Turtle graphics, Lists and Functions.
- #04☆☆☆
Hangman in Python
Learn Strings, Lists and while loops.
- #07☆☆☆
Mad Libs-Style Story Game in Python
Learn input() and print(), Strings and Variables.
- #08☆☆☆
Text Adventure Game in Python
Learn Dictionaries, Strings and while loops.
- #09☆☆☆
Connect Four-Style Game in Python
Learn 2D lists and grids, Lists and Functions.
- #11☆☆☆
Sudoku in Python
Learn 2D lists and grids, Functions and for loops.
- #12☆☆☆
Battleship-Style Game in Python
Learn 2D lists and grids, The random module and Strings.
- #13☆☆☆
Maze Game in Python
Learn 2D lists and grids, Functions and Lists.
- #15☆☆☆
Word Guessing Game in Python
Learn Strings, Lists and Dictionaries.
- #17☆☆☆
Turtle Race in Python
Learn Turtle graphics, Lists and for loops.
- #18☆☆☆
Python Quiz Game
Learn Dictionaries, Lists and for loops.
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.