Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list.index() versus dictionary

I have a list of about 50 strings. I will repeatedly (potentially tens of thousands of times) need to know the position of items in the list. Is it better to use list.index() each time, or create a dictionary mapping each item to its position? (My instinct says to create the dictionary, but I don't know what underlies the list indexing, and it may be superfluous.)

like image 847
PurpleVermont Avatar asked Dec 15 '22 17:12

PurpleVermont


1 Answers

list.index() will traverse the list until it finds the item it's looking for, which is a linear-time operation. Looking a string up in a dictionary, by contrast, is a constant-time operation, so the dictionary approach will likely have better performance.

Since your keys are strings and you have relatively few of them, another data structure you might want to explore is the trie.

like image 81
arshajii Avatar answered Dec 30 '22 09:12

arshajii