Python Tuples
A tuple is a fixed group of items in order, written in round brackets. A tuple cannot change after it is made.
A tuple in round brackets
Write the items in round brackets. Separate them with commas.
colors = ("red", "green", "blue")
print(colors)Count the items
len() works on a tuple just like on a list.
sizes = (10, 20, 30, 40)
print(len(sizes))One item needs a comma
Without a comma, round brackets just group a value.
one = (7,)
not_a_tuple = (7)
print(type(one))
print(type(not_a_tuple))
print(len(one))Build a tuple with tuple()
tuple() turns a list into a tuple.
letters = tuple(["a", "b", "c"])
print(letters)
print(len(letters))Example
birthday = (5, "May", 2012)
print(birthday[0])
print(birthday[1])
print(birthday[2])
print(len(birthday))Key points
- Tuple: a fixed group of items in order, written in round brackets
- Immutable: a word that means a value cannot change after you make it
- Use a tuple when the data should stay the same, like a date
- Use len() to count the items in a tuple
- Use tuple() to build a tuple from a list
- Without the comma, (7) is just the number 7 in brackets.
In this example, birthday holds one fixed date as a tuple. The day is 5, the month is May, and the year is 2012. birthday[0] prints the day, 5. birthday[1] prints the month, May. birthday[2] prints the year, 2012. len(birthday) prints 3, because the tuple holds three items.
Note
A one-item tuple needs its comma, like (7,).
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which code makes a tuple with one item?