Ryan
Ryan

Reputation: 133

Fastest way to search through lists in python

I’m sure there’s a standard answer for this. What’s the fastest method to loop over one list, forming a new list that is elements that are a member of a different list. I usually just do list comprehensions, sometimes turning the target list into a set. Hashing the target list usually improves performance when the target list is big, but this is the only improvement I know of. Any recommendations would be greatly appreciated.

list_A=list(range(0,100))
list_B=list(range(50,60))

#List comprehension lookup 
listC=[x for x in list_A if x in list_B]

#Using set
set_B=set(list_B))
listD=[x for x in list_A if x in set_B]

Upvotes: 0

Views: 362

Answers (1)

blue note
blue note

Reputation: 29081

If you don't care about order, you could hash both

set(listA) & set(listB)

Otherwise, not much you can do

Upvotes: 3

Related Questions