What is the difference between a List, Tuple, Set, and Dictionary in Python?
❓ Interview Prompt: Compare core Python data structures regarding mutability, ordering, uniqueness, indexing, and syntax.
Python provides four built-in collection data types:
| Data Structure | Syntax | Mutability | Ordered? | Duplicates Allowed? | Indexing |
|---|---|---|---|---|---|
| List | '[1, 2, 3]' | Mutable | Yes | Yes | By integer index |
| Tuple | '(1, 2, 3)' | Immutable | Yes | Yes | By integer index |
| Set | '{1, 2, 3}' | Mutable | No | No (Unique only) | None (hash-based) |
| Dict | '{"a": 1}' | Mutable | Yes (3.7+) | Keys: No, Values: Yes | By Key |
Why use an Immutable Tuple over a List?
Tuples have a smaller memory footprint, instantiate faster than lists, and can be hashed — making them valid candidates for dictionary keys or elements inside a Set!
Code Implementation Example
# 1. List: Mutable, ordered
users_list = ['Alice', 'Bob']
users_list.append('Charlie')
# 2. Tuple: Immutable record
coordinates = (10.5, 45.2)
# 3. Set: Unordered, unique elements only O(1) lookups
unique_ids = {101, 102, 101}
print(unique_ids) # {101, 102}
# 4. Dictionary: Key-value hash map
user_profile = {'username': 'alice_dev', 'role': 'admin'}Use Lists for ordered sequences, Tuples for immutable records, Sets for unique O(1) lookups, and Dicts for key-value maps.