Intern
In which cases do we use dictionaries, and in which - lists?
sobes.tech AI
Answer from AI
Lists are used when the order of elements matters and/or you need to store a collection of similar data with access by index. Lists are mutable.
Dictionaries are used when data is represented as key-value pairs and quick access to a value by its key is required. Keys must be immutable. Dictionaries are also mutable.
Comparison:
| Characteristic | List | Dictionary |
|---|---|---|
| Purpose | Ordered collection of elements | Collection of "key-value" pairs |
| Access | By index (integer) | By key |
| Order | Preserved (since Python 3.7) | Preserved (since Python 3.7) |
| Mutability | Mutable | Mutable |
| Use cases | Sequences, stacks, queues | Mappings, caches |
Examples:
List:
# List of names
names = ["Alice", "Bob", "Charlie"]
# Access by index
print(names[0])
Dictionary:
# Dictionary with user data
user_data = {"name": "Alice", "age": 30, "city": "New York"}
# Access by key
print(user_data["name"])