Tuples vs Lists

When to use each

Interview Relevant: Design decisions

Tuples vs Lists

Choose the right data structure.

Code Examples

When to use tuples vs lists.

python
1# Use TUPLE when:
2# - Data shouldn't change
3# - Using as dict key (hashable)
4# - Returning multiple values
5# - Heterogeneous data (x, y coordinates)
6
7point = (3, 4)
8locations = {(0, 0): "origin", (1, 1): "diagonal"}
9
10# Use LIST when:
11# - Collection may change
12# - Homogeneous data
13# - Need to sort, append, etc.
14
15names = ["Alice", "Bob", "Charlie"]
16names.append("David")
17names.sort()
18
19# Performance
20# Tuples are slightly faster and use less memory
21import sys
22sys.getsizeof([1, 2, 3])  # ~88 bytes
23sys.getsizeof((1, 2, 3))  # ~64 bytes

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In