0
How 'in' keyword in Python works?
I was to search whether an item is present in dictionary or not. So, what's the complexity of using this? I mean to ask the complexity while using the 'in' keyword. is it O(n) for the worst case ?
2 Respostas
+ 1
The in and not in operator works on dictionaries; it tells you whether something appears or not as a key in the dictionary. It returns two values True or False.
The in operator uses different algorithms for lists and dictionaries. For lists, it uses a search algorithm. As the list gets longer, the search time gets longer in direct
proportion. For dictionaries, Python uses an algorithm called a hashtable that has a remarkable property: the in operator takes about the same amount of time no matter how many items there are in a dictionary. I won’t explain how that’s possible, but you can read more about it at http://en.wikipedia.org/wiki/Hash_table.
0
example:
>>>dict={"hello":"hi","thank you":"your welcome"}
>>>"hello" in dict
True
>>>"hi" in dict
False