Choosing types
So far, you have learned about most of the common data structures in Python. One of the challenges you might face is knowing when to use the various data types.
When choosing a collection type, it is useful to understand the unique properties of that type. For example, a list is used to store multiple objects and to retain a sequence, a dictionary is used to store unique key-value pair mappings, tuples are immutable, and sets only store unique elements. Choosing the right type for a particular dataset could mean an increase in efficiency or security.
Consider the following examples:
- Defining points on the x-y coordinate plane:
- List
- Dictionary
- Tuple
- Set
Tuples are preferable for coordinate points that do not change, but some people prefer lists.
- List
- Dictionary
- Tuple
- Set
A list is better than a dictionary here because order matters.
- Finding unique numbers from a bunch of numbers:
- List
- Dictionary
- Tuple
- Set
Sets only include unique instances.
- Organizing a list of books and authors:
- List
- Dictionary
- Tuple
- Set
Dictionaries are ideal for storing attributes regarding people or things.
Although there may be more than one reasonable choice for a data structure, choosing an incorrect type for your data may lead to data loss or low efficiency while running your code, or in the worst case, losing your data altogether.