I like coding in Python, though I don’t really do too much of it. Last year I did some of Advent of Code 2020, which was challenging but interesting and rewarding. I’ve been meaning to write down a few of the things that I like about Python, with some examples from Advent of Code. Some of these are older features; some of them are newer — but they’re all useful!

List comprehension

introduced in Python 2.0, 2000

ints = [int(x) for x in nums]
{x for x in g if x != "\n"}
paths_to = {k: 0 for k in nums}
any(len(v) > 1 for v in allergens_to_ingredients.values())

Walrus operator

introduced in Python 3.8, 2019

if (m := mask[i]) == "X":
if mask[i] == "X":
m = mask[i]
if m == "X":


reduce() is a nice function which calls a function multiple times on a list. reduce(f, [a, b, c, d, e]) is equivalent to f(f(f(f(a, b), c), d), e) — effectively, reduce() is calling the function on the first pair of elements, and then calling it on the result of that and the next element. This can sound a bit confusing, and it definitely took me a while for me to get my head round it, but let’s look at an example from Day 16:

reduce(int.__mul__, your_ticket_values)

Chained comparison operators

Comparison, like iteration is just one of those really common programming tools, that just comes up again and again. Python has a handy trick for this too, called chained comparison — see Day 2.

if int(fr) <= password.count(letter) <= int(to):
if (int(fr) <= password.count(letter)) and (password.count(letter) <= int(to)):

Tuple assignment

Multiple assignment in Python is pretty well known — commonly discussed in the use case of ‘swapping’ variables, such as:

a, b = b, a
tmp = b
b = a
a = tmp
>>>foo = [2, 3, 4, 5, 6]
>>> first, *middle, last = foo
>>> first
>>> middle
[3, 4, 5]
>>> last
i_number, *i_colour, _ = inner_bag.split()