Intern / FresherPython

What is the difference between a list and a tuple in Python?

Quick answer

A list is mutable and can be changed after creation, while a tuple is immutable; tuples are slightly faster, use less memory and can be used as dictionary keys when their items are hashable.

Use a list for a collection that grows, shrinks or is reordered, such as the items in a shopping cart. Use a tuple for a fixed group of values that belong together, such as a coordinate (x, y) or a database row. Tuples also signal to the reader that the data should not change.

Immutability applies to the tuple itself: if a tuple contains a list, that list can still be modified. A one-item tuple needs a trailing comma, (5,), because (5) is just the number 5 in parentheses.

items = [1, 2, 3]
items.append(4)          # fine

point = (10, 20)
point[0] = 5             # TypeError: 'tuple' object does not support item assignment

locations = {(10, 20): "home"}   # tuples can be dict keys