Choose a Python list when order and changeability matter, a tuple for a fixed ordered group, a set for unique values and fast membership checks, and a dictionary for key-to-value lookup. The right choice depends on how you need to access, update, and compare your data—not simply on how many items it contains.
What Python collections do
Python’s built-in collections hold multiple values in a single object. They differ in whether items have a defined order, whether duplicates are allowed, how values are accessed, and whether the collection can be changed after creation.
Lists, tuples, sets, and dictionaries are all useful for everyday programming, but they are not interchangeable. A list and tuple store sequences; a set represents distinct elements; a dictionary associates keys with values. Choosing a structure that matches the task can make code clearer and prevent errors.
Lists: ordered, changeable sequences
A list keeps items in a defined order, allows duplicates, and can be modified. Use square brackets to create one. You can access an item by its zero-based index, slice a range, append new values, or replace and remove existing ones.
scores = [82, 91, 82]
scores.append(95)
scores[0] = 84
print(scores[1]) # 91
Lists suit data that may grow or change, such as a sequence of tasks, readings, or names. They also work well when position matters: the first item remains at index 0 unless the list is changed. A list can contain values of different types, though using a consistent type often makes a program easier to understand.
Lists permit repeated values, so the two occurrences of 82 above are both retained. Testing whether a value appears in a list typically checks elements one by one; for very large collections where membership checks dominate, a set may be a better fit.
Tuples: ordered groups that do not change
A tuple is an ordered sequence that cannot be modified after it is created. Parentheses are common, though commas—not parentheses alone—make a tuple. A one-item tuple therefore needs a trailing comma.
point = (3, 7)
single_item = (3,)
print(point[0]) # 3
Tuples are useful for fixed groups of related values, such as coordinates or a function returning several results. They support indexing and iteration like lists, and can contain duplicates. Since a tuple is immutable, you cannot assign a new value to one of its positions, append to it, or remove an element.
“Immutable” applies to the tuple’s contents as references: if a tuple contains a mutable object such as a list, that inner object can still change. Also, a tuple is hashable only when all its elements are hashable. Hashable tuples can be used as dictionary keys or set members; a tuple containing a list cannot.
Sets: distinct values and membership tests
A set stores distinct hashable elements and does not provide positional indexing. Adding a value that is already present does not create a duplicate. Sets are especially useful for removing duplicates, testing membership, and comparing groups with operations such as union and intersection.
colors = {"blue", "green", "blue"}
print(colors) # contains one "blue" and one "green"
print("green" in colors) # True
Do not rely on a set’s display or iteration order for a particular sequence. If you need an ordered sequence after removing duplicates, you can build a list from a set, but the resulting order should not be treated as the original order. If preserving first-seen order matters, a simple alternative is to track seen values while building a list.
An empty set is written as set(); {} creates an empty dictionary. Set elements must be hashable, so numbers, strings, and suitable tuples can be members, while lists and dictionaries cannot.
Dictionaries: keys mapped to values
A dictionary stores key-value pairs. Use a key to retrieve or update its associated value; keys must be unique and hashable, while values can be repeated and may be mutable. Dictionaries preserve insertion order in modern Python, but they are designed for lookup by key rather than by numeric position.
prices = {"tea": 3, "coffee": 4}
prices["tea"] = 3.5
prices["juice"] = 5
print(prices["coffee"]) # 4
Use a dictionary when each item has a meaningful label or identifier, such as a username mapped to a profile or a product name mapped to a price. The expression key in dictionary checks whether the key exists, not whether a value appears among the dictionary’s values. Use dictionary.get(key) when a missing key should return a default instead of raising KeyError.
Assigning a value to an existing key replaces that key’s previous value; it does not create a second entry with the same key. Keys such as lists are invalid because they are mutable and unhashable.
How to choose the right collection
Start with the operations your code needs. Ask whether order matters, whether repeated values are meaningful, how you will find an item, and whether the contents must change.
- Choose a list for an ordered sequence that may be edited and may contain duplicates.
- Choose a tuple for an ordered group that should not be reassigned after creation.
- Choose a set when each value should occur only once or membership and set comparisons are central.
- Choose a dictionary when you need to look up values using unique keys.
For example, a reading history could be a list if repeated readings and order matter. A fixed latitude-longitude pair could be a tuple. A collection of tags with no duplicates could be a set. A mapping from a tag to its description could be a dictionary.
These structures can be combined. A dictionary value might be a list of events, while a list might contain tuples representing coordinates. Choose the outer and inner structures independently according to how each part will be used.
Common mistakes and performance context
Lists and tuples use integer indexes; sets do not. Dictionaries use keys, and membership testing on a dictionary checks keys. Confusing these access patterns can lead to errors such as trying to index a set or expecting a dictionary to search its values.
For typical implementations, lists and tuples provide efficient indexed access, while checking whether a value is present in a set or a key is present in a dictionary is generally fast. These are broad performance characteristics, not guarantees that every operation takes identical time in every situation. Lists are often preferable for small sequences or when order and editing matter; changing to a set solely for speed can lose ordering and duplicate information.
Another common misconception is that tuples are automatically “better” or always use less memory than lists in a meaningful way. Their key distinction is immutability and intent: use a tuple to represent a fixed sequence, not just because it sounds more efficient. Likewise, converting data to a set removes duplicates, which may discard information your program needs.
Frequently Asked Questions
What is the difference between a list and a tuple in Python?
A list is mutable, so its contents can be added, removed, or replaced. A tuple is immutable, but both preserve sequence order, support indexing, and may contain duplicate values.
When should I use a set instead of a list?
Use a set when you need unique hashable values, set comparisons, or frequent membership checks and do not need positional indexing. Keep a list when order or duplicates matter.
Why does Python use curly braces for both sets and dictionaries?
Nonempty sets and dictionaries both use braces, but dictionaries contain key-value pairs such as {"a": 1}. An empty brace pair, {}, is an empty dictionary; create an empty set with set().
Can a list or dictionary be a set element or dictionary key?
No. Lists and dictionaries are mutable and unhashable, so they cannot be set elements or dictionary keys. Use an immutable, hashable alternative where appropriate, such as a tuple whose elements are also hashable.
Do Python dictionaries keep their order?
Yes. In modern Python, dictionaries preserve insertion order. That does not make them substitutes for lists when you need positional sequence operations; dictionaries are organized around key-value lookup.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Valheim Server Not Showing in Community List Fixes
- DisplayPort vs HDMI: Which Cable Should You Use?
- Soundbar vs 2.1 Speaker System: Which Is Better?
- Slack Channels for Construction Projects: Setup Guide
- Surface Won’t Turn On: Quick Fixes1.8 h
- Survive Lava for Brainrot Tier List170 points