Python Tuples: Create, Read and Why They Can't Change
What Is a Tuple in Python?
A tuple is a collection of values in a fixed order, written in round brackets (). It looks a lot like a list from chapter 9, with one big difference: once you make a tuple, it can't change.
point = (3, 5)
days = ("Mon", "Tue", "Wed")
print(point)
print(days)
print(type(days))(3, 5)
('Mon', 'Tue', 'Wed')
<class 'tuple'>Think of it like the date printed on a train ticket: day, month and year, always in that order, and nobody can rub it out and write a new one.
What you already know still works
Reading a tuple works exactly like reading a list:
| You write | It gives |
|---|---|
days[0] | the first item, "Mon" |
days[-1] | the last item, "Wed" |
days[0:2] | a new tuple with the first two items |
len(days) | the number of items, 3 |
"Tue" in days | True |
for day in days: | each item in turn |
days = ("Mon", "Tue", "Wed")
print(days[0], days[-1])
print(days[0:2])
print(len(days))
print("Sun" in days)
for day in days:
print("Open on", day)Mon Wed
('Mon', 'Tue')
3
False
Open on Mon
Open on Tue
Open on WedThe rules
- Items go inside round brackets, separated by commas.
- A tuple can mix types:
("Sunny", 25, True)holds a name, an age and a yes or no. - When you print a tuple, Python shows the round brackets, and strings get single quotes, as with lists.
- Indexes start at 0, and a missing index gives the same
IndexErroras a list.
Common beginner doubt: "Square or round brackets, does it matter?" Yes! The brackets decide the type. Square brackets [] make a list, round brackets () make a tuple. Everything else in this chapter comes from that one choice.
A tuple is a list in round brackets that can't change: same indexes, same len(), same in, same for loop.