What is the difference between a list and a tuple in Python?
Short answer
A list is mutable and written with []; a tuple is immutable and written with (). Use a tuple when the number of items is part of the meaning, or when you need a dictionary key.
scores = [88, 92, 79] # list — you expect this to grow
point = (1920, 1080) # tuple — a width and a height, always exactly two#What immutability buys you
They can be dictionary keys. Lists cannot, because a key's hash must never change.
grid = {(0, 0): "start", (3, 4): "goal"}They are safe to share. A tuple passed into a function cannot be modified behind your back.
They signal intent. Finding a third item in a coordinate pair would be a bug. Making it a tuple means it cannot happen.
#Unpacking works on both
width, height = point
first, *rest = scores#The gotcha
A tuple is shallowly immutable. The tuple cannot change, but a mutable object inside it still can:
data = ([1, 2], "fixed")
data[0].append(3) # works — the list inside is still mutable
data[1] = "other" # TypeError#Single-item tuples need a trailing comma
not_a_tuple = (5) # just the number 5
actual_tuple = (5,) # a one-item tuple