7 ms·
Let's say you are writing a python program, and you want to simply check if an element is in a list. So, you build a list and then check if 'd' is in the list:
by itsmemattchung 10y ago
Let's say you are writing a python program, and you want to simply check if an element is in a list. So, you build a list and then check if 'd' is in the list:
mylist = ['a','b','c','d'].
if 'd' in mylist:
...
This works just fine, however, the time it takes, to find the item, grows proportional to the number of items in the list. If your list grows to 1000 items, and the item you are searching for is positioned last, python will check 1000 times. This is known as O(N).
Now, how does the performance compare, when using a set data structure?
myset = ('a','b','c','d')
if 'd' in myset:
...
Well, underneath the hood, the set stores the data in what's known as a hash. The time it takes to check if an item is (or isn't) in a list does not grow proportional to the number of items in the list—it's always constant: O(1).