Fastest Way to Check If a Value Exists in a List

Fastest way to check if a value exists in a list

7 in a

Clearest and fastest way to do it.

You can also consider using a set, but constructing that set from your list may take more time than faster membership testing will save. The only way to be certain is to benchmark well. (this also depends on what operations you require)

Fastest way to check if a list is present in a list of lists

Using a list comprehension with set.

Ex:

a=[[1,2,3,4,5,6],[7,8,9,10,11,12]]  
b=[[5, 9, 25, 31, 33, 36],[7,8,9,10,11,12],[10, 13, 22, 24, 33, 44]]

setA = set(map(tuple, a))
setB = set(map(tuple, b))

print([i for i in setA if i not in setB])

Output:

[(1, 2, 3, 4, 5, 6)]

Fastest way to check whether a value exists more often than X in a list

Here is the Counter-based solution:

from collections import Counter

items = [2,3,4,1,2,3,4,1,2,1,3,4,4,1,2,4,3,1,4,3,4,1,2,1]
counts = Counter(items)
print(all(c >= 5 for c in counts.values())) #prints True

If I use

items = [random.randint(1,1000) for i in range(300000)]

The counter-based solution is still a fraction of a second.

Fastest way to check if a item is in a list - Python

Unless you need vocab to have a particular order, you can just do:

vocab = set(words)

Fastest way to iterate over a list and see if element exists?

Your current time complexity is O(NxM) where

N = len(ids_as_string )

M = len(url_list )

What you can do is, re-organise your data-structure in to maps

{id : url}

Example, process your 'id_123' into map, looking at your code, I assume id's are unique in URLs.
like

lookup_map = {
'123' : "http://www.url.com/test/dont-find-me/id_123",
'124' : "http://www.url.com/test/dont-find-this/id_124"
<so on>
}

To process this, time complexity is O(N) N is length of url list.

the just do

for id in ids_as_string:
if id in lookup_map:
<OK>

each 'if in' look-up takes O(1) so, Total complexity: O(N) + O(M)

Most efficient way to find if a value exists within a C# List

Use either list.Contains(true) or list.Any(true).
For a normal list both have complexity O(n). Since Any() is an extension method though, which needs to invoke delegates, the Contains() might still be a bit faster. But to be sure I would simply test both with a large collection.



Related Topics



Leave a reply



Submit