How 'in' keyword in Python works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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 ?

3rd Jan 2017, 5:01 AM
Ayush Saluja
Ayush Saluja - avatar
2 Answers
+ 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.
3rd Jan 2017, 8:40 PM
Victor Prohnitchi
Victor Prohnitchi - avatar
0
example: >>>dict={"hello":"hi","thank you":"your welcome"} >>>"hello" in dict True >>>"hi" in dict False
3rd Jan 2017, 7:06 AM
ali.gh
ali.gh - avatar