Reputation: 1127
Suppose I have a list list1
of about 1 000 000 sub-lists. Next, I would like to check if the given element a
, which is a sub-list, exists in the list. Normally, it would be enough to check using if a in list1
, but with a large list it works quite slowly. Is there another way?
Upvotes: 0
Views: 124
Reputation: 48745
Since you state you can use tuples, I would recommend making each of your sub-lists into tuples and then making a set
of these tuples. Then, searching the set
will be an O(1) lookup. Initial construction of the set may be costly, though, but if you do many lookups it is worth it.
>>> set_of_sublists = {tuple(sublist) for sublist in orignal_list}
>>> tuple(sublist_to_check_for_membership) in set_of_sublists
I want to acknowledge that @BrettBeatty originally gave this answer as well but has deleted it subsequently.
Upvotes: 1