Learn Data Structures and Algorithms in Python

Data structures are ways to store data (lists, sets, dictionaries, grids, queues) and algorithms are step-by-step methods that work on them (searching, recursion, backtracking). The fastest way to learn them in Python is to see each one doing a real job, so on this page every idea is shown inside a game you can play and rebuild.

Most data structures and algorithms (DSA) courses start with abstract diagrams. Here we start with games, because a game makes it obvious why a structure exists: a snake needs a list, a maze solver needs a queue, a Sudoku solver needs backtracking. Every example below runs right on the page.

šŸ’” You'll get the most from this page once you know the Python basics: loops, if statements and functions. New to those? Start with how long it takes to learn Python and the concept pages.

Data structures and algorithms at a glance

IdeaWhat it's forWhere you'll see it
ListAn ordered row of items you can grow and shrinkSnake's body
SetFast "is this in here?" checks, no duplicatesHangman, Mine Finder
DictionaryLook things up by nameLighthouse Island, Rock Paper Scissors
2D gridRows and columns of cellsFour in a Row, Sudoku
Queue + breadth-first searchShortest pathsMaze Runner's solver
Recursion + depth-first searchExploring until a dead endMaze Runner's generator, Mine Finder's flood fill
BacktrackingTry, and undo when it failsThe Sudoku solver
Binary searchHalve the options every stepNumber Guessing strategy

Lists: the snake's body

A list keeps items in order. In Snake, the body is a list of positions with the head first. Moving adds a new head with insert(0, ...) and removes the tail with pop(); eating food simply skips the pop, so the snake grows.

example 1 Ā· press Run, then edit and run again

Good to know: adding or removing at the end of a Python list is fast, while inserting at the front shifts every item. For a short snake that doesn't matter; for long queues you'll use a deque (below).

Sets: guessed letters and mines

A set stores unique items and answers x in s almost instantly, however big it gets. Hangman keeps the guessed letters in a set; Mine Finder keeps the mine positions in one. Set maths does the rest: & finds what two sets share, - what one has that the other doesn't.

example 2 Ā· press Run, then edit and run again

Dictionaries: rules and rooms

A dictionary maps keys to values, so you look things up by name instead of position. Rock Paper Scissors stores what each move beats; the text adventure stores every room and its exits. Lookups stay fast even with thousands of keys.

example 3 Ā· press Run, then edit and run again

2D grids: game boards

A grid is a list of rows, and grid[row][col] reads one cell. Board games check lines by stepping in a direction, like Four in a Row looking for four matching counters. Read the grids guide for the common traps (such as copying rows by accident).

example 4 Ā· press Run, then edit and run again

Queues and breadth-first search: the shortest way out

Breadth-first search (BFS) explores in rings: every square 1 step away, then 2, then 3. A queue keeps the order: new squares join the back, and the next one to explore comes off the front. Because it spreads evenly, the first time BFS reaches the exit is the shortest path. Python's collections.deque is a fast queue.

example 5 Ā· press Run, then edit and run again

Play with this in Maze Runner: type solve and BFS draws the route.

Recursion and depth-first search: flood fill

A recursive function calls itself on a smaller part of the problem. Depth-first search (DFS) uses it to go as deep as possible before backing up. Mine Finder's flood fill is a perfect example: open an empty square, then open its neighbours, and theirs, until you reach numbers. The seen set stops it going round in circles.

example 6 Ā· press Run, then edit and run again

Maze Runner uses the same idea to build its mazes: dig to a random unvisited neighbour, recurse, and back up at dead ends.

Backtracking: the Sudoku solver

Backtracking is recursion with an undo button: place a choice, try to solve the rest, and if that fails, take the choice back and try the next one. It solves puzzles like Sudoku. Here it fills a mini 4Ɨ4 Sudoku (numbers 1-4 once in every row, column and 2Ɨ2 box):

example 7 Ā· press Run, then edit and run again

The full-size version is the third challenge on the Sudoku game page.

Binary search: always win the guessing game

Binary search finds a target in a sorted range by checking the middle and throwing away the half that can't contain it. Each guess halves what's left, so finding a number from 1 to 100 never takes more than 7 guesses. It's the perfect strategy for the Number Guessing Game:

example 8 Ā· press Run, then edit and run again

Big-O in plain words

Big-O describes how the work grows when the data grows. You don't need the maths to use it:

Big-OIn plain wordsExample from the games
O(1)Same time however big the dataletter in guessed with a set
O(log n)Halves the problem each stepBinary search in the guessing game
O(n)Looks at each item onceChecking every square of a board
O(n²)Each item against every otherComparing every pair of squares
ExponentialDoubles (or worse) with each extra choiceBacktracking on a hard puzzle

Practise with the matching challenges

Each of these games ends with coding challenges that check your answer, including flood() in Mine Finder, distance() with breadth-first search in Maze Runner and a full backtracking solve() in Sudoku:

Frequently asked questions

What is the best way to learn data structures and algorithms in Python?

Learn each one by using it: build something where the structure is needed, such as a snake that is a list or a maze solver that uses a queue. Then practise with small, checked exercises before moving to harder problems.

Which data structures should I learn first in Python?

Lists, dictionaries and sets, because Python has them built in and you'll use them every day. Then grids (lists of lists), queues with collections.deque, and stacks.

Do I need to know algorithms to make games in Python?

Not for simple games, but a few algorithms appear again and again: breadth-first search for pathfinding, recursion for flood fill and maze generation, and backtracking for puzzle solvers.

Is Python good for learning data structures and algorithms?

Yes. Its short syntax lets you focus on the idea instead of the code around it, and it is accepted in most coding interviews.

How long does it take to learn data structures and algorithms?

After the Python basics, plan on a few weeks for the core structures and common algorithms on this page, and a few months of regular practice to use them confidently on new problems.

More beginner questions

Keep going

Ready to practise? Follow the 4-week plan to learn Python with games, browse all 20 Python games, or see every beginner question in Learn Python.