BugHunt

TypeError: unhashable type: 'list'

You used a list where Python needs a value that can never change: in a set, as a dictionary key, or in a set or dict lookup. Use a tuple instead.

PythonType errors

What it means

Sets and dictionaries find items by their hash, and a hash is only valid while the value stays the same. Lists can be changed, so Python refuses to hash them. Newer versions add context, such as "cannot use 'list' as a set element". Tuples, strings and numbers are hashable; lists, dicts and sets are not.

Common causes

1. Adding a list to a set

Common when collecting coordinates or pairs.

Breaks

seen = set()
seen.add([x, y])

Works

seen = set()
seen.add((x, y))

2. Using a list as a dictionary key

Keys must be hashable for the same reason.

Breaks

visits = {}
visits[[lat, lng]] = 1

Works

visits = {}
visits[(lat, lng)] = 1

3. Removing duplicates from a list of lists

set() has to hash every element, and the elements are lists.

Breaks

unique = set(pairs)

Works

unique = {tuple(p) for p in pairs}

How to find it in your own code

The failing line is the one that hashes: set(), .add(), a dictionary key, or `in` on a set or dict. Convert the value with tuple(value) before storing it, and back with list() only if you need to change it later.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors