Tuples
Tuples - immutable lists
Tuples
A tuple is a sequence of values, just like a list. The key difference is that tuples are immutable — once created, they cannot be changed. You cannot add, remove, or modify elements.
Creating a Tuple
Use parentheses instead of square brackets:
You can also create a tuple without parentheses — just commas are enough:
Python sees the comma and creates a tuple automatically. The parentheses are optional in most cases, but it's good practice to include them for clarity.
Single-element Tuple
This is a common gotcha — a single value in parentheses is not a tuple:
You must include a trailing comma to make a single-element tuple.
Indexing and Slicing
Tuples support the same indexing and slicing as lists:
Immutability
You cannot modify a tuple after creation:
This is the fundamental restriction. If you need to change values, use a list.
Tuple Unpacking
This is where tuples really shine. You can unpack a tuple into separate variables in one line:
This works with any number of elements:
You have already been using this without realizing it — whenever you write a, b = map(int, input().split()), map returns an iterable that gets unpacked into a and b.
Swapping Variables
Tuple unpacking makes swapping two variables a one-liner in Python — no temporary variable needed:
In C++ you need a temporary variable for this. In Python, the right side is evaluated as a tuple first, then unpacked.
What You Can Do with Tuples
Tuples support all read operations that lists support:
When to Use Tuples vs Lists
Use a list when your collection may change — you plan to append, remove, or modify elements.
Use a tuple when your collection is fixed — coordinates, RGB values, a pair of values you want to unpack, or a key in a dictionary.
In competitive programming tuples come up most often in two situations: unpacking multiple return values from a function, and as keys in dictionaries.