brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python checks in on a set thousands of times faster than on a list

Python
~/tips/tip-python-set-membership-speed

known = set(load_known_ids()) # convert once

Speed up repeated membership checks by turning the lookup list into a set.

One of the cheapest speedups I know in Python: if code asks x in something over and over, make sure that something is a set and not a list.

known = set(load_known_ids())     # convert once
new = [row for row in rows if row["id"] not in known]

That’s the shape it usually has in real code: a loop that skips items it has already seen. With a list, every not in searches from front to back, so the time grows with the length. A set looks the item up by hash and takes about the same time whether it holds ten items or a million. A dict gives you the same fast lookup on its keys.

You can see the gap with timeit:

python3 -m timeit -s "big = list(range(100_000))" "99_999 in big"
python3 -m timeit -s "big = set(range(100_000))" "99_999 in big"

In a test run the first took around 500 microseconds per check and the second about 11 nanoseconds. With a few thousand rows on each side, that one set() call can turn a script that takes minutes into one that’s done before you look up.

Sets have no order and no duplicates, and items must be hashable, so lists or dicts can’t go inside. Building the set also costs a pass over the data, so for a single check on a short list I wouldn’t bother.

Further reading: Set types, TimeComplexity (Python wiki)

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link