Last updated
Python Tuples
Definition: A tuple is an ordered collection like a list, but it cannot be changed after it is created. It is written with round brackets ( ).
point = (4, 5) print(point) print(point[0]) # 4
List vs tuple — when to use which
- List
[ ]— data that may change (add/remove/edit) - Tuple
( )— fixed data that should never change, like coordinates or weekdays
Example 1 — tuples are read-only
colors = ("red", "green", "blue")
print(colors[1]) # green
print(len(colors)) # 3
# colors[0] = "yellow" # this line would cause an error
Example 2 — unpacking a tuple
Split a tuple into separate variables in one line:
person = ("Sam", 25)
name, age = person
print(name) # Sam
print(age) # 25
Example 3 — returning several values
Functions often return a tuple to give back more than one value (you will see this later).
coords = (10, 20)
x, y = coords
print("x is", x, "and y is", y)
💡 Why tuples? Because they cannot change, they are safer for constants and slightly faster than lists.
Try it Yourself
Output
Ad · responsive