I have a line of code like so:
event = [x for x in history if x.serial == serialized_event]
In all circumstances in my application, the resulting list will only ever contain a single item. But it seems to me it is going to iterate over the entire "history" list anyway looking for all possible matches.
This is unnecessary, especially since in most cases it will find what I'm looking for within the first few indices and it will effectively be the only result.
How can I make this more efficient?
x.serial
sorted?history
? Can you optimize that? For example dictionaries and sets have O(1) time complexity for membership checks. However if you always find the result in the first couple of indices it doesn't sound like this is a bottle neck so optimizing may end up costing more than it saves.