Python workbook
Use List
1. When you need to mutate your collection.
2. When you need to remove or add new items to your collection of items.
Use Tuple
1. If your data should or does not need to be changed.
2. Tuples are faster than lists. We should use a Tuple instead of a List if we are defining a constant
set of values and all we are ever going to do with it is iterate through it.
3. If we need an array of elements to be used as dictionary keys, we can use Tuples. As Lists are
mutable (unhashable type), they can never be used as dictionary keys.
When to use Set vs. List/Tuple?
As Set uses Hash Table as its underlying data structure, Set is blazingly fast when it comes to checking if
an element is inside it (e.g. x in a_set).
The idea behind it is that looking up an item in a hash table is an O(1) (constant time) operation.
"So, should I always use Set or Dictionary?"
Essentially, if you do not need to store duplicates, Set is going to be better than List. Period.
Summary
If you’re a numbers geek like me, check out this speed comparison between Tuple, List, and Set when
iterating or checking if an object is present in a collection.
What are the main takeaways?
If you need to store duplicates, go for List or Tuple.
For List vs. Tuple, consider mutability. If you need immutability, go for Tuple.
If you do not need to store duplicates, always go for Set or Dictionary. Hash maps are
significantly faster when it comes to determining if an object is present in the Set (e.g. x in
set_or_dict).