Questions
What is the difference between a list and a tuple in Python?
The Scenario
You are a backend engineer at a social media company. You are writing a new service that needs to store a collection of items. You are not sure whether to use a list or a tuple to store the items.
The Challenge
Explain the difference between a list and a tuple in Python. What are the pros and cons of each approach, and which one would you choose for this use case?
A junior engineer might think that they are interchangeable. They might not be aware of the difference in mutability or the performance implications of choosing one over the other.
A senior engineer would be able to provide a detailed explanation of the differences between lists and tuples. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.
Step 1: Understand the Key Differences
| Feature | List | Tuple |
|---|---|---|
| Mutability | Mutable, can be changed after it is created. | Immutable, cannot be changed after it is created. |
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Performance | Slower than tuples. | Faster than lists. |
| Use Cases | When you need a collection of items that can be changed. | When you need a collection of items that should not be changed. |
Step 2: Choose the Right Tool for the Job
For our use case, it depends on whether we need to be able to change the collection of items after it is created.
- If we need to be able to add or remove items from the collection, we should use a list.
- If the collection of items will not change, we should use a tuple.
Step 3: Code Examples
Here are some code examples that show the difference between the two approaches:
List:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # [1, 2, 3, 4]Tuple:
my_tuple = (1, 2, 3)
# This will raise an error, because tuples are immutable
# my_tuple.append(4) Practice Question
You want to use a collection of items as a key in a dictionary. Which of the following would you use?