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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With