Python TuplesGet Certified
What Is a Tuple?
A tuple is an ordered collection of items, very much like a list, with one big difference: a tuple is immutable. Once it is created, you cannot add, remove, or replace its items. In Python the type is called tuple, and a tuple is usually written with parentheses and commas, as in (3, 4). Tuples are the natural choice for a small group of values that belong together and should not change: the coordinates of a point, a date as year, month, and day, or an RGB color.
- Ordered: every item has an index that starts at 0, and indexing and slicing work as for lists.
- Immutable: the items of a tuple cannot be changed after the tuple is created.
- Any types: a tuple can mix numbers, strings, and other objects, and it can contain duplicates.
- Unpacking: assign the items of a tuple to several variables in one statement.
- Hashable: a tuple of immutable items can be used as a dictionary key or a set member, which a list cannot.
- Everywhere in Python: functions such as
divmod(),enumerate(), andzip()produce tuples.
Creating Tuples
Write the items separated by commas, usually inside parentheses. It is the comma that makes a tuple, not the parentheses. This is why a tuple with one item needs a trailing comma: (5,) is a tuple, but (5) is just the number 5 in parentheses. An empty tuple is written (). The tuple() function converts another iterable, such as a string, a list, or a range, into a tuple. The parentheses may be left out in simple cases, so point = 3, 4 also creates a tuple. This is called tuple packing.
Try It: Creating and Reading Tuples
Click Test My Code. Pay attention to the types of single and not_a_tuple.
tuple().point = (3, 4)
colors = ("red", "green", "blue")
single = (5,)
not_a_tuple = (5)
empty = ()
print(point[0], colors[-1])
print(type(single), type(not_a_tuple))
print(len(colors), len(empty))
print(tuple("abc"), tuple([1, 2]))point refers to a tuple with two items.colors refers to a tuple of three strings. Its indexes are 0, 1, and 2.not_a_tuple is just the integer 5.() is a tuple with no items.point[0] is the first item and colors[-1] is the last. The output is 3 blue.<class 'tuple'> <class 'int'>.len() counts the items. The output is 3 0.tuple("abc") splits the string into its characters, and tuple([1, 2]) turns the list into a tuple. The output is ('a', 'b', 'c') (1, 2).Immutability, Slicing, and Operators
Reading from a tuple works just like reading from a list. Indexing, slicing with [start:stop:step], len(), in, + for joining, and * for repeating are all available. Operations that would change the tuple are not. Assigning to an index, or calling append(), remove(), or sort(), raises an error. Joining and repeating do not break this rule, because they create a new tuple and leave the old one alone. A tuple has only two methods: count(x) returns how often a value appears, and index(x) returns the position of the first match.
Try It: Reading, Joining, and Trying to Change
Click Test My Code. The try and except lines catch the error so that the program can continue. You will learn how they work in the lesson on errors and exceptions.
TypeError, which the program catches and prints. Finally it uses in, index(), and count().t = (10, 20, 30, 40, 50)
print(t[1:4], t[::-1])
print(t + (60,), t * 2)
try:
t[0] = 99
except TypeError as error:
print("Error:", error)
print(20 in t, t.index(30), t.count(10))t holds five items with the indexes 0 to 4.t[1:4] takes the positions 1, 2, and 3. t[::-1] walks through the tuple backwards. Slices of a tuple are tuples. The output is (20, 30, 40) (50, 40, 30, 20, 10).t + (60,) creates a new tuple with one more item, and t * 2 creates a new tuple with the items repeated. The original t is not touched. The output is (10, 20, 30, 40, 50, 60) (10, 20, 30, 40, 50, 10, 20, 30, 40, 50).except line instead of stopping the program.TypeError.except TypeError as error: catches the error and stores it in the variable error.Error: 'tuple' object does not support item assignment.20 in t is True. t.index(30) is the position of 30, which is 2. t.count(10) is 1. The output is True 2 1.Tuple Unpacking
Unpacking assigns the items of a tuple to separate variables in a single statement. The number of variables must match the number of items, or Python raises a ValueError. A variable marked with * collects any extra items into a list. By convention the name _ marks a value that you do not need. Unpacking works with lists and any other iterable too, and it is the reason why you can swap two variables with a, b = b, a: the right side is first packed into a tuple and then unpacked.
Try It: Unpacking and Swapping
Click Test My Code. Then remove one name from the line name, age, city = ... and read the error.
_.point = (3, 4)
x, y = point
print(x, y)
first, *middle, last = (1, 2, 3, 4, 5)
print(first, middle, last)
a, b = 1, 2
a, b = b, a
print(a, b)
name, age, city = ("Asha", 21, "Delhi")
print(f"{name} is {age} and lives in {city}")
_, second, _ = (7, 8, 9)
print(second)point refers to the tuple (3, 4).x and the second goes to y.3 4.first gets the first item and last gets the last item. The starred middle collects everything in between as a list.1 [2, 3, 4] 5.1, 2 is a tuple without parentheses, and it is unpacked into a and b.(2, 1), and then assigned to a and b. No temporary variable is needed.2 1.Asha is 21 and lives in Delhi._ signals that a value is not needed. Only the middle item is kept, in second.8.Tuples Everywhere: Functions That Return Pairs
You use tuples all the time, often without noticing. The built-in divmod(a, b) returns the quotient and remainder as a tuple. zip() produces a tuple for each position, enumerate() produces a tuple of an index and an item, and the dictionary method items() produces a tuple of a key and a value. This is why a for loop can unpack two variables at once: each item that the loop receives is a tuple. A function can also return several values by separating them with commas. Python packs them into one tuple, and the caller unpacks them.
Try It: Tuples from Built-in Functions
Click Test My Code. Notice how each loop unpacks a tuple into two variables.
divmod(), collects pairs from zip(), loops over those pairs, loops over enumerate() to get indexes, and shows the key and value pairs of a dictionary.quotient, remainder = divmod(17, 5)
print(quotient, remainder)
print(divmod(17, 5))
pairs = list(zip(["a", "b", "c"], [1, 2, 3]))
print(pairs)
for letter, number in pairs:
print(letter, number)
for index, fruit in enumerate(("apple", "kiwi")):
print(index, fruit)
prices = {"tea": 3, "coffee": 5}
print(list(prices.items()))divmod(17, 5) returns the tuple (3, 2), which is unpacked into quotient and remainder.3 2.(3, 2).zip() pairs the first letter with the first number, and so on. list() collects the pairs into a list of tuples.[('a', 1), ('b', 2), ('c', 3)].pairs is a tuple, and the loop unpacks it into letter and number.a 1, b 2, and c 3.enumerate() produces tuples of an index and an item. The loop unpacks them into index and fruit.0 apple and 1 kiwi.prices refers to a dictionary with two entries.items() gives each entry as a tuple of a key and a value. The output is [('tea', 3), ('coffee', 5)].Tuples Versus Lists
Tuples and lists look similar, so how do you choose?
- Use a list for a collection of similar items whose number or content changes, such as a list of scores or a to-do list.
- Use a tuple for a fixed group of values that belong together, especially when each position has its own meaning, such as
(x, y)or(name, age, city). - Tuples protect their data from accidental changes, and they use a little less memory than lists.
- Only tuples of immutable items can be dictionary keys and set members.
Immutability applies only to the tuple itself: it cannot swap which objects it holds. If one of those objects is mutable, such as a list, that object can still change. To “change” a tuple, convert it to a list with list(), change the list, and convert back with tuple().
Try It: Converting and a Mutable Surprise
Click Test My Code. Look closely at the last line: the tuple data seems to have changed even though tuples are immutable.
nums = (5, 2, 9, 1)
print(sorted(nums))
print(tuple(sorted(nums)))
print(min(nums), max(nums), sum(nums))
as_list = list(nums)
as_list.append(7)
print(as_list)
print(tuple(as_list))
data = ([1, 2], 3)
data[0].append(99)
print(data)nums holds four numbers in no particular order.sorted() always returns a new list, even when it is given a tuple. The output is [1, 2, 5, 9].tuple() gives a sorted tuple. The output is (1, 2, 5, 9).1 9 17.list(nums) creates a list with the same items. The list can be changed, and the tuple stays the same.[5, 2, 9, 1, 7].(5, 2, 9, 1, 7).data is a tuple whose first item is a list.data[0] is the list, and append() changes that list. The tuple still holds the very same list, so no rule is broken.([1, 2, 99], 3). Because of this, a tuple that contains a list cannot be used as a dictionary key.Tuples as Dictionary Keys
An object that can be used as a dictionary key or set member must be hashable: it needs a fixed value that never changes. Tuples of numbers and strings are hashable, so they are perfect for keys that have several parts, such as grid positions or latitude and longitude pairs. A list is not hashable, and using one as a key raises a TypeError. Two tuples with equal items are equal, and have the same hash.
Try It: Hashable Tuples
Click Test My Code. Add the pair (1, 2) to the set once more and check that the length does not change.
locations = {(0, 0): "origin", (1, 2): "park"}
print(locations[(1, 2)])
print((0, 0) in locations)
print(hash((1, 2)) == hash((1, 2)))
seen = {(1, 2), (3, 4), (1, 2)}
print(len(seen))
try:
bad = {[1, 2]: "list key"}
except TypeError as error:
print("Error:", error)(1, 2) finds its value. The output is park.in checks the keys of the dictionary. The output is True.True.(1, 2) is written twice, but it is stored once.2.TypeError.TypeError.error.Error: unhashable type: 'list'.Comparing and Sorting Tuples
Tuples are compared item by item, from left to right, like words in a dictionary. Python looks at the first items. If they differ, that decides the result. If they are equal, it moves to the second items, and so on. This makes it easy to sort records: when a tuple starts with the score, sorting a list of tuples sorts by score, and the later items break ties. Because of this rule, max() and min() also work on a list of tuples.
Try It: Item-by-Item Comparison
Click Test My Code. Change (1, 2, 4) to (1, 2, 3) and predict the second line.
==, <, and >. It then sorts a list of (score, name) tuples from the highest score to the lowest, finds the largest tuple with max(), and sorts pairs of letters and numbers where the first item ties.print((1, 2, 3) == (1, 2, 3))
print((1, 2, 3) < (1, 2, 4))
print((2, 0) > (1, 99))
results = [(90, "Asha"), (72, "Ben"), (85, "Chen")]
results.sort(reverse=True)
print(results)
print(max(results))
print(sorted([("b", 2), ("a", 9), ("b", 1)]))True.3 < 4 decides the result. The output is True.2 > 1 already decides the result. The second items are never compared, so 99 does not matter. The output is True.reverse=True puts the largest first.[(90, 'Asha'), (85, 'Chen'), (72, 'Ben')].max() compares the tuples in the same way and returns the one with the highest score. The output is (90, 'Asha')."b" tuples tie on the first item, so the second items decide: 1 comes before 2. The output is [('a', 9), ('b', 1), ('b', 2)].Named Tuples
A plain tuple makes you remember what each position means. Is p[0] the x coordinate or the y coordinate? A named tuple, from the collections module, gives each position a name. It is still a real tuple, so it is immutable and works with indexing and unpacking, but you can also read its items by name. Use _replace() to make a modified copy, and _asdict() to convert it to a dictionary.
Try It: A Named Tuple
Click Test My Code. Add a third field named "z" to the list and give the point three numbers.
Point type with the fields x and y, creates a point, and reads its items by name and by index. It unpacks the point like a normal tuple, makes a changed copy with _replace(), and converts the point to a dictionary.from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p)
print(p.x, p[1])
x, y = p
print(x + y)
print(p._replace(x=10))
print(p._asdict())namedtuple is a factory function from the collections module.namedtuple("Point", ["x", "y"]) creates a new tuple type called Point with two named fields. The result is stored in the variable Point.Point(3, 4) creates a tuple with x = 3 and y = 4.Point(x=3, y=4).p.x reads the item by name, and p[1] reads it by position. The output is 3 4.x and y.7._replace() does not change p. It returns a new point with x replaced. The output is Point(x=10, y=4)._asdict() returns the fields and their values as a dictionary. The output is {'x': 3, 'y': 4}.Tip: When you create a tuple that will not change, a tuple signals your intention to the reader of your code. Choose a tuple for fixed records and a list for collections that grow or shrink. If you find yourself writing record[2] over and over, a named tuple will make the code much easier to read.
Using Tuples with User Input
Tuples are a good fit for data made of a fixed number of parts. Read a line, split it, and unpack the parts straight into variables. Remember that input() always returns text, so convert the words that should be numbers.
Try It: Distance Between Two Points
The Program Input box is already filled with 0 0 6 8. Click Run Code straight away, then try the numbers 1 2 4 6.
math.dist() to calculate the distance between them, and builds a tuple for the midpoint.import math
values = input("Enter x1 y1 x2 y2: ").split()
x1, y1, x2, y2 = map(float, values)
p1 = (x1, y1)
p2 = (x2, y2)
print("Point 1:", p1)
print("Point 2:", p2)
print("Distance:", math.dist(p1, p2))
midpoint = ((x1 + x2) / 2, (y1 + y2) / 2)
print("Midpoint:", midpoint)math module provides dist().input() reads the line, and split() turns it into the list ["0", "0", "6", "8"].map(float, values) converts each word to a float, and the four results are unpacked into four variables. The line fails with a ValueError if the number of values is not four.p1 is the tuple (0.0, 0.0).p2 is the tuple (6.0, 8.0).Point 1: (0.0, 0.0).Point 2: (6.0, 8.0).math.dist() takes two points and returns the straight-line distance between them. For a right triangle with sides 6 and 8, the distance is 10. The output is Distance: 10.0.Midpoint: (3.0, 4.0).Try It: Reading a Record
The Program Input box is filled with asha,21,delhi. Click Run Code, then enter your own name, age, and city separated by commas.
record = tuple(input("Enter name,age,city: ").split(","))
print("Record:", record)
name, age, city = record
print(f"{name.title()} is {age} years old and lives in {city.title()}")
age = int(age)
record = (name, age + 1, city)
print("Next year:", record)
print("Fields:", len(record))split(",") cuts the text at each comma, and tuple() turns the resulting list into a tuple of three strings.Record: ('asha', '21', 'delhi'). Note that the age is still text.name, age, and city.title() capitalizes the first letter of a word. The output is Asha is 21 years old and lives in Delhi.int(age) turns the text "21" into the number 21.age + 1, and the name record is pointed at it.Next year: ('asha', 22, 'delhi').Fields: 3.Common Mistakes with Tuples
- Forgetting the comma in a one-item tuple:
(5)is the number 5. Write(5,). - Trying to change a tuple:
t[0] = 1raises aTypeError, andt.append(1)raises anAttributeError. Build a new tuple, or convert to a list, change it, and convert back. - Unpacking the wrong number of items:
a, b = (1, 2, 3)raises aValueError. Match the count, or use a starred variable such asa, *rest = .... - Thinking that a tuple is deeply frozen: a list inside a tuple can still change. Use immutable items when the whole structure must stay fixed.
- Using a tuple that contains a list as a dictionary key: it is not hashable and raises a
TypeError. - Building a big tuple by repeated
+=: every+=creates a whole new tuple, which is slow for large data. Collect the items in a list and calltuple()once at the end. - Expecting
sorted()to return a tuple: it always returns a list. Wrap it intuple()if you need a tuple. - Choosing a tuple for data that must grow: if items are added or removed during the program, a list is the right tool.
Key Takeaways
- A tuple is an ordered, immutable collection. Its items cannot be added, removed, or replaced after creation.
- The comma makes the tuple: a one-item tuple needs a trailing comma, as in
(5,). - Indexing, slicing,
len(),in,+, and*work like for lists. The only methods arecount()andindex(). - Unpacking assigns the items to several variables at once, with
*to collect extras and_for values you ignore. - Functions such as
divmod(),zip(),enumerate(), anddict.items()produce tuples. - Tuples of immutable items are hashable, so they can be dictionary keys and set members.
- Tuples are compared item by item, and
namedtupleadds readable field names.
Frequently Asked Questions
What is a tuple in Python?
A tuple is an ordered, immutable collection of items written with commas, usually inside parentheses, such as (3, 4). It supports indexing and slicing like a list, but its items cannot be changed after it is created.
How do I create a tuple with one item in Python?
Add a trailing comma after the item, for example single = (5,). Without the comma, (5) is just the number 5 in parentheses, not a tuple.
What is the difference between a list and a tuple in Python?
A list is mutable and written with square brackets, so its items can be added, removed, and changed. A tuple is immutable and written with parentheses. Tuples are suited to fixed groups of values, they can be used as dictionary keys, and they protect data from accidental changes.
Can I change a tuple in Python?
Not directly. Assigning to an item raises a TypeError. To get a modified version, convert the tuple to a list with list(), change the list, and convert it back with tuple(), or build a new tuple by slicing and joining.
What is tuple unpacking in Python?
Tuple unpacking assigns the items of a tuple to separate variables in one statement, for example x, y = (3, 4). The number of variables must match the number of items. A variable with a star, as in first, *rest = items, collects the extra items into a list.
Why would I use a tuple instead of a list?
Use a tuple for a fixed group of related values, such as coordinates or a record with several fields. A tuple tells the reader that the data should not change, it uses slightly less memory, and, unlike a list, it can be used as a dictionary key or a set member.
How do I convert between a list and a tuple in Python?
Use tuple(my_list) to convert a list to a tuple and list(my_tuple) to convert a tuple to a list. Both functions also accept other iterables, such as strings and ranges.
Can a tuple be used as a dictionary key in Python?
Yes, as long as all the items inside the tuple are immutable, for example numbers and strings. Such a tuple is hashable. A tuple that contains a list is not hashable, and using it as a key raises a TypeError.