Tuple in Python
A tuple is an ordered collection like a list, but it cannot be changed once created, which makes it a good fit for fixed groups such as coordinates.
What is Tuple?
A tuple is an ordered collection like a list, but it cannot be changed once created, which makes it a good fit for fixed groups such as coordinates.
Group values in a tuple, unpack them and return several values from a function.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
See how it works
A tuple is fixed once it is created. Try to change it, then unpack its values into separate variables.
Example code
# A tuple is an ordered collection that cannot be changed after it is created.
point = (3, 4)
colors = ("red", "green", "blue")
print(point[0], point[1])
print(len(colors), colors[-1])
# Unpacking assigns each item to its own variable.
x, y = point
print(f"x = {x}, y = {y}")
# Functions can return several values as a tuple.
def min_max(values):
return min(values), max(values)
low, high = min_max([7, 2, 9, 4])
print(low, high)
# Swap two variables without a temporary one.
a, b = 1, 2
a, b = b, a
print(a, b)
# Trying to change a tuple raises an error.
try:
point[0] = 10
except TypeError as error:
print("Error:", error)
Expected output
3 4
3 blue
x = 3, y = 4
2 9
2 1
Error: 'tuple' object does not support item assignment
How it works
Unpacking assigns each item to its own variable, which is also how a function returns several values and how a, b = b, a swaps two variables.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Min and Max Together Find the smallest and largest value in one pass. Easy
- Swap First and Last Exchange the first and last items of a list. Easy