PythonCore language
What is the difference between a list and a tuple in Python?
Question 1 of 6 · Updated
A list is mutable: you can add, remove or change items after it is created. A tuple is immutable: once created, its items cannot be reassigned.
PYTHONnums = [1, 2, 3] nums.append(4) # fine point = (3, 4) point[0] = 5 # TypeError: 'tuple' object does not support item assignment
When to use which
- Use a list for a collection that changes, such as items being collected in a loop.
- Use a tuple for a fixed record, such as
(lat, lng)or a function returning several values. - Because tuples are immutable (and hashable when their items are), they can be dictionary keys or set members. Lists cannot.
Tuples are also slightly smaller in memory and a little faster to create, but readability and intent are the real reasons to choose one.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design