Choosing the Right Collection#
| Use This | When You Need | Example |
|---|---|---|
| list | Ordered items, duplicates OK, will modify | Shopping cart items |
| tuple | Ordered items that won't change, hashable | Coordinates (x, y) |
| dict | Key-value lookup, fast access by key | User profiles by ID |
| set | Unique items only, fast membership testing | Seen URLs, tags |
Quick decision: Start with list. Switch to dict if you need lookup by key, set if you need uniqueness, or tuple if the data shouldn't change.
Lists#
Lists are Python's most versatile built-in data structure — ordered, mutable sequences that can hold items of any type. They are the go-to choice for storing and manipulating ordered collections of data.
Lists
Creating and manipulating ordered collections
Tuples#
Tuples are ordered, immutable sequences — once created, their elements cannot be changed. This immutability makes them hashable (usable as dictionary keys), slightly more memory-efficient than lists, and ideal for representing fixed collections like coordinates or database records.
Tuples
Immutable ordered sequences
Dictionaries#
Dictionaries map unique keys to values, providing O(1) average-time lookups. They are one of Python's most important data structures, ideal for representing structured data, caches, and any key-value relationship. Since Python 3.7, dictionaries maintain insertion order.
Dictionaries
Key-value mappings
Sets#
Sets are unordered collections of unique elements, optimized for fast membership testing and mathematical set operations like union, intersection, and difference. Use sets when you need to eliminate duplicates or check if items exist in a collection.
Sets
Unordered collections of unique elements