In Python, list, tuple, set, and dictionary are built-in data structures used to store collections of values. Each serves a distinct purpose based on mutability, ordering, and uniqueness requirements.
Lists are ordered, mutable sequences that allow duplicates. Tuples are ordered, immutable sequences also allowing duplicates. Sets are unordered collections of unique elements. Dictionaries are unordered mappings of keys to values, where keys must be unique and immutable.
Lists maintain insertion order and support indexing and slicing. You can modify their contents after creation using assignment, append(), insert(), or remove().
Tuples behave similarly but cannot be changed after creation. This immutability makes them safe for use as dictionary keys or function return values.
Sets automatically eliminate duplicate entries and do not preserve order. They support mathematical operations like union, intersection, and difference.
Dictionaries map unique keys to values. Keys must be hashable (e.g., strings, numbers, tuples), and values can be any type. Access is via key lookup, not index.
Each structure uses different underlying mechanisms:
| Type | Order | Mutable? | Unique Items? | Use Case |
|---|---|---|---|---|
| List | Yes | Yes | No | Ordered sequence of items, e.g., shopping list |
| Tuple | Yes | No | No | Fixed data, e.g., RGB color codes (255, 128, 0) |
| Set | No | Yes | Yes | Membership testing, removing duplicates |
| Dictionary | No | Yes | Keys only | Key-value mapping, e.g., user profiles |
For example, a list of student grades: [85, 92, 78, 92] allows repeated scores. A tuple of geographic coordinates: (40.7128, -74.0060) remains unchanged. A set of unique usernames: {'alice', 'bob', 'charlie'} removes duplicates. A dictionary maps usernames to roles: {"alice": "admin", "bob": "user"}.
Use lists when order matters and changes are expected. For example, tracking daily temperatures over a week: [72, 75, 68, 71, 73, 70, 74].
Tuples are ideal for fixed data. The Python standard library uses them extensively-os.path.split() returns a tuple of directory and filename.
Sets excel in membership checks. Checking if a username exists in a large list takes O(n) time. Using a set reduces it to O(1) average case. This matters in applications like login systems.
Dictionaries store structured data. Consider a program managing employee records:
employees = {
"E001": {"name": "Sarah", "role": "engineer"},
"E002": {"name": "Tom", "role": "manager"}
}
Accessing Sarah's role is employees["E001"]["role"].
Many assume sets and dictionaries are interchangeable because both use curly braces. But {1, 2, 3} is a set; {1: "one", 2: "two"} is a dictionary. Mixing them causes syntax errors.
Another mistake: thinking lists can be dictionary keys. Only immutable types can be keys. Trying my_dict = {[1, 2]: "value"} raises TypeError. Use a tuple instead: {(1, 2): "value"}.
A non-obvious fact: sets are faster than lists for checking existence. With 100,000 items, searching a list takes ~0.002 seconds. A set takes ~0.000001 seconds. This speed difference becomes critical in loops.
Suppose you have a log file with user IDs and actions. You want to find all unique users who performed a specific action.
Raw data:
events = [
("U101", "login"),
("U102", "logout"),
("U101", "view"),
("U103", "login"),
("U102", "login")
]
Extract unique users who logged in:
logins = {user for user, action in events if action == "login"}
print(logins) # Output: {'U101', 'U103'}
This uses a set comprehension. The result is a set-no duplicates, fast lookup.
If you later need to track which users performed multiple actions, use a dictionary:
action_count = {}
for user, action in events:
action_count[user] = action_count.get(user, 0) + 1
print(action_count) # Output: {'U101': 2, 'U102': 2, 'U103': 1}
Using dict.get() avoids KeyError when counting.
I once processed a dataset of 500,000 user sessions. Initially, I stored session IDs in a list. Checking for duplicates took over 10 seconds. Switching to a set reduced it to under 0.1 seconds. The change was straightforward: replace session_ids = [] with session_ids = set() and use add() instead of append().
Choose based on these criteria:
For example, storing a playlist of songs: use a list for order. Storing a collection of favorite tracks: use a set to avoid duplicates. Tracking song popularity: use a dictionary with song titles as keys and counts as values.
Understanding the differences between list, tuple, set, and dictionary in Python prevents bugs and improves performance. These structures are foundational to effective Python programming.