Computer Science · Ch 5 — Getting Started with Python
Deciding Usage of Python Data Types
Deciding Usage of Python Data Types
Python offers four collection types — list, tuple, set, dictionary — and each has a situation in which it is the preferred choice. The deciding questions are: will the data change, must entries be unique, and how will the data be looked up?
Lists — for data that changes often
Prefer a list when we need a simple iterable collection that may go through frequent modifications. Example: storing the names of students of a class. Students join and leave during the year, and a list is easy to update each time:
students = ["Anita", "Farid", "Meera"]
students.append("Rohan") # a new student joins
# students is now ["Anita", "Farid", "Meera", "Rohan"]
Tuples — for data that must not change
Use a tuple when no change in the data is needed. Example: the names of the months in a year — a fixed, ordered collection that no program should ever alter:
months = ("January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December")
Sets — for uniqueness
When we need uniqueness of elements and want to avoid duplicacy, a set is preferable. Example: the list of artefacts in a museum — each artefact should appear exactly once, and a set enforces that automatically:
artefacts = {"bronze seal", "terracotta lamp", "coin hoard"}
Dictionaries — for keyed, fast lookup
Reach for a dictionary when the data is constantly modified, or we need a fast lookup based on a custom key, or there is a logical association between key : value pairs. A mobile phone book is a good application of a dictionary — names are the keys, numbers the values, and any number is retrieved instantly by name: