Ordered intersection of two lists in Python

set_2 = frozenset(list_2)
intersection = [x for x in list_1 if x in set_2]

set instead of frozenset works too, I’m just increasingly in the habit of using immutable classes in cases where I don’t intend to mutate the data. The point is that to maintain order you need to traverse the list in the order you want to maintain, but you don’t want to have the n*m complexity of the naive approach: [x for x in list_1 if x in list_2]. Checking for membership in a set or similar hash-based type is roughly O(1), compared to O(n) for membership in a list.

Leave a Comment