list vs tuple
list is a mutable sequence you can modify, while tuple is an immutable sequence that can be a dictionary key or a set element.
Side-by-side comparison
#Syntax
Can be changed after creation
A dictionary key or a set element
Modifying methods (append, sort, …)
Memory use and creation speed
Typical use
Example
#tasks = ["HTML", "CSS"]
tasks.append("JavaScript")
point = (3, 4)
print(tasks)
print(point)
try:
point[0] = 10
except TypeError as error:
print(error)Definition and usage
#Both collections store elements in a fixed order and support the same read operations: indexing, slicing, len(), in, a for loop, and unpacking. The elements of either one can have different types.
What sets them apart is mutability. You create a list with square brackets, and you can modify it with methods like append(), remove(), sort(), and others. You create a tuple with parentheses (a one-element tuple needs a comma: (x,)), and once created it can’t be changed: you can’t add, remove, or swap an element. Thanks to that immutability, a tuple can be a dictionary key and a set element, which a list can’t.
When the data is meant to change while the program runs, for example a to-do list or results appended in a loop, choose list. When the data is inherently fixed, for example a point’s coordinates, a row from a database, or the result of a function returning several values at once, choose tuple. Immutability also works as documentation: a tuple tells you this data won’t change.
Syntax
#my_list = [1, 2, 3]
my_tuple = (1, 2, 3)More examples
#distances = {}
distances[(0, 0)] = 0
distances[(1, 2)] = 5
print(distances)
try:
distances[[1, 2]] = 5
except TypeError as error:
print(type(error).__name__)A list has no hash, so it can’t be a key. The exact error message text depends on the Python version, but the TypeError type is always the same.
list_values = ["Emma", 7]
tuple_values = ("Jack", 3)
name1, level1 = list_values
name2, level2 = tuple_values
print(name1, level1)
print(name2, level2)Good practices
#- A function returning several values (
return a, b) creates a tuple. You unpack it the same way as a list. - The functions
list()andtuple()convert between the two. - If a list should never change, a tuple is also a signal to other developers that the data is fixed.
Related entries
#Spotted a mistake or missing an example? Write to us.