Every December, thousands of programmers wake up early (or stay up late) for Advent of Code: a run of Christmas-themed programming puzzles by Eric Wastl. Python is one of the most popular languages for it, because it reads input easily and has a standard library full of the tools these puzzles need.
This guide gets you ready for Advent of Code 2026 in Python: a starter template, the input-parsing patterns that come up again and again, the standard library modules worth knowing, and ready-to-use searches for grids and graphs. Everything here is general Python, not puzzle solutions.
When does Advent of Code 2026 start?
According to the Advent of Code about page, puzzles start on 1 December and a new one unlocks every day at midnight US Eastern time (UTC−5). That is 05:00 UTC, 10:45 in Nepal and 10:30 in India.
Two things changed recently, so older guides may be out of date:
- It's shorter than it used to be. Until 2024 there were 25 puzzles, one a day up to Christmas. In 2025 the event moved to 12 puzzles, ending in mid-December, and the about page now describes the event as ending mid-December too.
- There is no global leaderboard any more. It was removed in 2025. Private leaderboards, for you and your friends or team, still work.
Each puzzle has two parts. You get your own puzzle input (a text file), and the second part unlocks after you solve the first. Please don't share your input or the puzzle text publicly: the about page asks people not to.
A starter template
Keep one file per day. This template reads the input, runs both parts, and also runs them on the example from the puzzle, which is the fastest way to catch mistakes:
import time
def parse(text):
return text.strip().splitlines()
def part1(data):
return len(data)
def part2(data):
return 0
EXAMPLE = """\
line one
line two
"""
if __name__ == "__main__":
print("example:", part1(parse(EXAMPLE)), part2(parse(EXAMPLE)))
with open("input.txt") as f:
data = parse(f.read())
for part in (part1, part2):
start = time.perf_counter()
answer = part(data)
print(f"{part.__name__}: {answer} ({time.perf_counter() - start:.3f}s)")Write parse() first, check it on the example, then fill in part1(). When part 2 arrives, the parsed data is already there.
Reading the input
Almost every puzzle input is one of a few shapes. These one-liners cover most of them:
| Input looks like | Python |
|---|---|
| One item per line | lines = text.splitlines() |
| One number per line | nums = [int(x) for x in text.split()] |
| Groups separated by a blank line | groups = [g.splitlines() for g in text.strip().split("\n\n")] |
| Comma-separated numbers | nums = list(map(int, text.split(","))) |
| Numbers mixed with words | nums = list(map(int, re.findall(r"-?\d+", line))) |
| A grid of characters | grid = text.splitlines(), then grid[row][col] |
The regular expression trick is the most useful of all. It pulls every number out of a line, whatever words and symbols are around it:
import re
line = "Sensor at x=12, y=-4: closest beacon is at x=-2, y=15"
print(list(map(int, re.findall(r"-?\d+", line))))The output:
[12, -4, -2, 15]Grids
Grids appear in nearly every year. A handy way to store one is a dictionary from (row, col) to the character. Then you never go out of range by accident: grid.get(pos) simply returns None outside the grid.
text = """\
#..#
.#..
..#."""
grid = {(r, c): ch for r, line in enumerate(text.splitlines()) for c, ch in enumerate(line)}
walls = [pos for pos, ch in grid.items() if ch == "#"]
print(len(grid), "squares,", len(walls), "walls")
def neighbours(pos):
r, c = pos
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
if (r + dr, c + dc) in grid:
yield (r + dr, c + dc)
print(list(neighbours((0, 0))))The output:
12 squares, 4 walls
[(1, 0), (0, 1)]For diagonal neighbours too, add (-1, -1), (-1, 1), (1, -1), (1, 1) to the list of directions.
The standard library toolbox
You rarely need to install anything. These modules come up again and again:
| Tool | What it's for |
|---|---|
collections.Counter | Count things: Counter("hello").most_common(1) |
collections.defaultdict | Dictionaries of lists or counts without KeyError |
collections.deque | A fast queue for breadth-first search |
heapq | Always take the smallest item next (Dijkstra, scheduling) |
functools.cache | Remember the results of a recursive function |
itertools.combinations / permutations / product | Try every pair, order or combination |
itertools.pairwise | Look at neighbours in a list: (a, b), (b, c), ... |
math.gcd, math.lcm | Cycles that line up again after a while |
re | Pull numbers and words out of messy lines |
functools.cache deserves a special mention. Part 2 of a puzzle is often part 1 with much bigger numbers, and a recursive solution that repeats work becomes instant with one line:
from functools import cache
@cache
def ways(n):
if n < 0:
return 0
if n == 0:
return 1
return ways(n - 1) + ways(n - 2) + ways(n - 3)
print(ways(50))The output:
10562230626642Without @cache, that call would take far too long. With it, each ways(n) is worked out once.
Breadth-first search: the shortest path in steps
When every move costs the same (one step), breadth-first search finds the shortest path. It explores everything 1 step away, then 2 steps, and so on:
from collections import deque
def shortest_steps(grid, start, goal):
queue = deque([(start, 0)])
seen = {start}
while queue:
pos, steps = queue.popleft()
if pos == goal:
return steps
r, c = pos
for nxt in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if grid.get(nxt, "#") != "#" and nxt not in seen:
seen.add(nxt)
queue.append((nxt, steps + 1))
return -1
text = """\
..#.
.##.
...."""
grid = {(r, c): ch for r, line in enumerate(text.splitlines()) for c, ch in enumerate(line)}
print(shortest_steps(grid, (0, 0), (0, 3)))The output:
7Dijkstra: the cheapest path when steps cost different amounts
When moves have different costs, swap the queue for a heap, so the cheapest route so far is always explored first:
import heapq
def cheapest(grid, start, goal):
best = {start: 0}
heap = [(0, start)]
while heap:
cost, pos = heapq.heappop(heap)
if pos == goal:
return cost
if cost > best[pos]:
continue
r, c = pos
for nxt in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if nxt in grid:
new = cost + int(grid[nxt])
if new < best.get(nxt, float("inf")):
best[nxt] = new
heapq.heappush(heap, (new, nxt))
return -1
text = """\
131
919
111"""
grid = {(r, c): ch for r, line in enumerate(text.splitlines()) for c, ch in enumerate(line)}
print(cheapest(grid, (0, 0), (2, 2)))The output:
6Here each digit is the cost of stepping onto that square (the start is free). The cheapest way goes through the 1 in the middle: 3 + 1 + 1 + 1 = 6, which avoids both 9s.
Tips that save the most time
- Run the example first. If your answer on the example is wrong, your real answer will be too, and the example is small enough to check by hand.
- Read the whole puzzle before coding. The last paragraph often changes what the question really is.
- Expect part 2 to scale up. If part 1 uses a loop that tries everything, part 2 may need a smarter idea: caching, maths, or noticing a repeating cycle.
- Print small things. A quick
print()of the parsed input catches most bugs before they get confusing. - Don't race. With no global leaderboard, there is no prize for speed. Solving the puzzle and understanding it is the whole point.
Warm up with Advent of Python 2026
Want daily practice before and alongside Advent of Code? **Advent of Python 2026** is our free Christmas Python calendar: one challenge a day from 1 to 25 December, starting with warm-ups and finishing with hard puzzles that use exactly the tools above, including breadth-first search, Dijkstra, topological sort and dynamic programming. Each one runs in your browser with hidden tests, so there's nothing to install.
You can also try any snippet from this page in the Python playground, or work through the Python coding challenges for more practice.
*Advent of Code is a registered trademark of Eric Wastl. PythonExecutor is not affiliated with Advent of Code.*