Is there any performance advantage to using lists over dictionaries over tuples in Python?
If I'm optimising for speed, is there any reason to prefer one over another?
Is there any performance advantage to using lists over dictionaries over tuples in Python?
If I'm optimising for speed, is there any reason to prefer one over another?
Tuples will be slightly faster to construct for a small number of elements. Although actually most of the gains will be in memory used rather than CPU cycles, since tuples require less space than lists.
With that being said, the performance difference should be negligible, and in general you shouldn't worry about these kinds of micro-optimizations until you've profiled your code and identified a section of code that is a bottleneck.
The big difference is that tuples are immutable, while lists and dictionaries are mutable data structures. This means that tuples are also faster, so if you have a collection of items that doesn't change, you should prefer them over lists.
Rich,
Lists and dicts are beasts suitable for different needs. Make sure you don't use lists for linear searches where dicts hashes are perfect, because it's way slower. Also, if you just need a list of elements to traverse, don't use dicts because it will take much more space than lists.
That may sound obvious, but picking the correct data structures algorithmically has much higher performance gains that micro-optimization due to more efficient compiled code layouts, etc. If you search in a list in O(n) instead of in a dict in O(1), micro-optimizations won't save you.