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(), in and 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 20
Packing 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
BasisListTuple
Syntax[1, 2, 3](1, 2, 3)
MutabilityMutableImmutable
MethodsMany (append, remove, sort …)Only count() and index()
MemoryUses more memoryUses less memory
Dictionary keyNot allowed (unhashable)Allowed if all items are immutable
Typical useCollections that changeFixed 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() and index(); 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.

Q1. Which of the following creates a tuple with ONE element?

Show Answer

Correct Answer : C. (5,)
The trailing comma makes it a tuple.

Q2. Which of these operations is NOT allowed on a tuple?

Show Answer

Correct Answer : D. t.append(4)
Tuples are immutable and have no append() method.

Q3. What is the output of print((1, 2, 2, 3).count(2))?

Show Answer

Correct Answer : A. 2
The value 2 occurs twice.

Q4. After a, *b = (1, 2, 3), what is b?

Show Answer

Correct Answer : B. [2, 3]
A starred target always collects items into a list.

Q5. Which can be used as a dictionary key?

Show Answer

Correct Answer : D. (1, 2)
A tuple of immutable items is hashable.

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.

  1. Python Software Foundation. (n.d.). Data Structures. In The Python Tutorial. https://docs.python.org/3/tutorial/datastructures.html
  2. Python Software Foundation. (n.d.). Built-in Types. The Python Standard Library. https://docs.python.org/3/library/stdtypes.html
  3. Python Software Foundation. (n.d.). Glossary. Python 3 Documentation. https://docs.python.org/3/glossary.html
  4. Python Software Foundation. (n.d.). Data Model. In The Python Language Reference. https://docs.python.org/3/reference/datamodel.html
  5. Lutz, M. (2013). Learning Python (5th ed.). O’Reilly Media.