The short answer
Both a list and a tuple hold an ordered collection of items in Python. A list can change: you can replace items, add them and remove them. A tuple cannot have its items replaced once it exists. Lists are written with square brackets, and tuples with parentheses (or just commas).
Written side by side
numbers = [3, 4] # a list
point = (3, 4) # a tuple
Both hold two numbers, and in both the position of each number matters.
Changing and growing
numbers[0] = 10 # fine: lists can be changed
numbers.append(5) # fine: lists can grow
point[0] = 10 # TypeError: 'tuple' object does not support item assignment
point.append(5) # AttributeError: 'tuple' object has no attribute 'append'
Each of the two tuple lines raises an error when it runs, so a program would stop at the first one.
When to use each
- Use a tuple for a fixed group of values where position gives the meaning, such as an (x, y) coordinate or a (year, month, day) date.
- Use a list for a collection that changes, such as a shopping list or a list of scores that keeps growing.
- Use a tuple as a dictionary key. A tuple works as a key when its items can be hashed, but a list does not. For example,
grid = {(0, 0): "start"}is valid, while{[0, 0]: "start"}raisesTypeError: unhashable type: 'list'.
The C++ comparison
C++ has two types that look similar at first:
std::vectorcan grow and shrink, but every element has the same type.std::tuplehas a fixed size, and each element can have its own type.
#include <tuple>
#include <vector>
std::vector<int> numbers{3, 4};
numbers.push_back(5); // fine: a vector can grow
std::tuple<int, int> point{3, 4}; // the size is fixed by the type
For a fixed size where every element has one type, see “What is std::array in C++?”