Learning Objectives – after this chapter you will be able to:
- Create tuples, including empty and single-element tuples.
- Index, slice and loop over tuples.
- Explain immutability and use packing and unpacking.
- Choose between a tuple and a list.
What is a Tuple?
- A tuple is an ordered, immutable collection, usually written in parentheses:
(10, 20, 30). - Like lists, tuples allow duplicates and mixed types, and support indexing, slicing,
len(),inand looping. - Unlike lists, a tuple cannot be changed after it is created: no append, remove or item assignment.
point = (4, 7)
colors = ("red", "green", "blue", "green")
empty = ()
single = (5,) # the comma makes it a tuple
not_a_tuple = (5) # just the integer 5 in brackets
also_tuple = 1, 2, 3 # brackets are optional
print(type(single), type(not_a_tuple))
print(also_tuple, len(empty))
print(colors[1], colors[-1], colors[1:3])Output
<class 'tuple'> <class 'int'>
(1, 2, 3) 0
green green ('green', 'blue')Immutability
days = ("Mon", "Tue", "Wed")
try:
days[0] = "Sun"
except TypeError as e:
print("Error:", e)
# To "change" a tuple, build a new one
days = ("Sun",) + days[1:]
print(days)
# A tuple can contain a mutable object, which itself can change
record = ("Asha", [80, 90])
record[1].append(75)
print(record)Output
Error: 'tuple' object does not support item assignment
('Sun', 'Tue', 'Wed')
('Asha', [80, 90, 75])Tuple Methods and Operations
Tuples have only two methods: count(x) and index(x).
t = (3, 1, 4, 1, 5, 9, 1)
print(t.count(1), t.index(4))
print(len(t), min(t), max(t), sum(t))
print((1, 2) + (3,), ("hi",) * 3)
print(4 in t, sorted(t)) # sorted() returns a list
for value in (10, 20):
print(value, end=" ")Output
3 2
7 1 9 24
(1, 2, 3) ('hi', 'hi', 'hi')
True [1, 1, 1, 3, 4, 5, 9]
10 20Packing and Unpacking
Packing puts several values into one tuple; unpacking assigns the items of a tuple to separate variables. A starred name (*rest) collects the remaining items into a list.
student = ("Ravi", 19, "BCA") # packing
name, age, course = student # unpacking
print(name, age, course)
first, *rest = (1, 2, 3, 4)
print(first, rest)
def stats(nums):
return min(nums), max(nums) # returns a tuple
lo, hi = stats([8, 3, 11])
print(lo, hi)Output
Ravi 19 BCA 1 [2, 3, 4] 3 11
Tuple vs List
| Basis | List | Tuple |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutability | Mutable | Immutable |
| Methods | Many (append, remove, sort …) | Only count() and index() |
| Memory | Uses more memory | Uses less memory |
| Dictionary key | Not allowed (unhashable) | Allowed if all items are immutable |
| Typical use | Collections that change | Fixed records, e.g. coordinates, dates, RGB colours |
import sys
print(sys.getsizeof([1, 2, 3]) > sys.getsizeof((1, 2, 3)))
distances = {("Bhopal", "Indore"): 195}
print(distances[("Bhopal", "Indore")])
print(list((1, 2)), tuple([3, 4]))Output
True 195 [1, 2] (3, 4)
Key Takeaways
- Tuples are ordered and immutable; a single-item tuple needs a trailing comma.
- Only
count()andindex(); unpacking assigns items to variables. - Use tuples for fixed data and as dictionary keys; lists for data that changes.
Video : Tuples
Question / Answer (15 questions)
Answer : A tuple is an ordered, immutable collection of items, usually written in parentheses, e.g. (10, 20, 30). It allows duplicates and items of different types but cannot be changed after creation.
Answer : Add a trailing comma: single = (5,). Without the comma, (5) is just the integer 5 in parentheses.
Answer : No. The commas create the tuple; t = 1, 2, 3 is a tuple. Parentheses are needed only for the empty tuple () or where the expression would otherwise be ambiguous.
Answer : Python raises TypeError: 'tuple' object does not support item assignment, because tuples are immutable.
Answer : You cannot change it in place, but you can build a new tuple from parts of the old one, e.g. days = ("Sun",) + days[1:], or convert it to a list, change the list and convert back with tuple().
Answer : Yes. The tuple itself cannot be changed to refer to different objects, but a mutable object inside it, such as a list, can still be modified, e.g. record[1].append(75).
Answer : Only two: count(x), which returns how many times x occurs, and index(x), which returns the position of the first occurrence of x.
Answer : Packing is grouping values into a tuple: student = ("Ravi", 19, "BCA"). Unpacking is assigning its items to variables: name, age, course = student.
Answer : first receives 1 and the starred name rest receives the remaining items as a list: [2, 3, 4].
Answer : Dictionary keys must be hashable. Tuples containing only immutable items are hashable; lists are mutable and therefore unhashable.
Answer : Lists use [] and are mutable; tuples use () and are immutable. Lists have many methods while tuples have only count() and index(). Tuples use less memory. Tuples (of immutable items) can be dictionary keys; lists cannot.
Answer : When the data is fixed and should not change, such as coordinates, dates, RGB colours or records returned from a function, and when you need a dictionary key.
Answer : return a, b returns the tuple (a, b), which the caller can unpack: lo, hi = stats(nums).
Answer : ('hi', 'hi', 'hi') – repetition creates a new tuple with the items repeated three times.
Answer : No. sorted() always returns a new list. Use tuple(sorted(t)) to get a sorted tuple.
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.
- Python Software Foundation. (n.d.). Data Structures. In The Python Tutorial. https://docs.python.org/3/tutorial/datastructures.html
- Python Software Foundation. (n.d.). Built-in Types. The Python Standard Library. https://docs.python.org/3/library/stdtypes.html
- Python Software Foundation. (n.d.). Glossary. Python 3 Documentation. https://docs.python.org/3/glossary.html
- Python Software Foundation. (n.d.). Data Model. In The Python Language Reference. https://docs.python.org/3/reference/datamodel.html
- Lutz, M. (2013). Learning Python (5th ed.). O’Reilly Media.