Introduction to Collections
A single variable holds one value, but a collection holds many. The most common collection is the list (or array), an ordered sequence of values stored under one name.
scores = [90, 85, 70, 100]
Each element occupies a position called its index. Indices almost universally start at 0: scores[0] evaluates to 90, while the final element of a four-item list sits at scores[3] rather than scores[4].
The length of a list is its total number of elements. Lists support adding, removing, updating items, and iterating through them using loops.
Lists vs Dictionaries
A dictionary (or map) stores key-value pairs, allowing fast lookups by name or ID instead of numeric position.
ages = {"Ana": 30, "Ben": 25}
| Feature | List | Dictionary |
|---|---|---|
| Access | By numeric index | By unique key |
| Order | Strictly ordered sequence | Unordered by position |
| Use Case | Ordered items & sequences | Key-based lookups |
Common Pitfall: Forgetting that indices start at 0. For a list of length n, valid indices range from 0 to n-1. Accessing index n triggers an index-out-of-range error.