This is exactly why you need to take some algorithms and data structures
lecture. Who in their right mind would think that checking if a key is present
in a hash map takes O(n) time by generating a list of all keys and linear
search when extracting the value from under that key takes O(1)?
Hello, I've had Data Structures, while on BSc and implemented by hand hashmaps.. If you read the post you would understand the doubt.
Try the following:
a = [i for in range(10000)]
if 9999 in a:
print('yay I just looped over an entire array')
however:
a = {i:i for in range(10000)}
if 9999 in a:
print('yay I found a key in linear time')
Now, You might be an expert in Data Structures, but what makes you implicitly know how the 'IN' behaves in python, and that it won't convert to the keys() method of the dict to get a list with the same behaviour as in a list?
> [...] what makes you implicitly know how the 'IN' behaves in python, and that it won't convert to the keys() method of the dict to get a list with the same behaviour as in a list?
Because it would be the dumb way to do it. You have a lookup procedure to
extract a value from a hash. A procedure to check if the key is present in the
hash will look exactly the same, barring the value being returned.
Libraries usually work the same way as you would write yourself if you were
trained in the task, so it's easy to guess.
Use try..except.. when you expect it to mostly succeed.
$ python -m timeit -s "a={k:k for k in range(10000)}" 'try:
b=a[10001]
except:
pass'
1000000 loops, best of 3: 0.276 usec per loop
$ python -m timeit -s "a={k:k for k in range(10000)}" 'try:
b=a[1]
except:
pass'
10000000 loops, best of 3: 0.0255 usec per loop