Academic Block

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(), and zip() 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.

What this code does: It creates a pair, a tuple of three strings, a one-item tuple, a plain number in parentheses, and an empty tuple. It prints items by index, compares the types of the one-item tuple and the plain number, prints the lengths, and converts a string and a list with 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]))

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.

What this code does: It takes slices of a tuple, joins and repeats tuples to build new ones, and then tries to assign to an item. The assignment fails with a 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))

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.

What this code does: It unpacks a pair into two variables, collects the middle items of a longer tuple with a starred name, swaps two variables, unpacks a record of three fields into a formatted message, and ignores unwanted items with _.
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)

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.

What this code does: It unpacks the result of 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()))

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.

What this code does: It sorts a tuple, which gives a list, and converts the list back to a tuple. It prints the smallest, largest, and total. It then “changes” a tuple by converting it to a list and back, and finally shows that a list stored inside a tuple can still be modified.
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)

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.

What this code does: It builds a dictionary whose keys are coordinate pairs and looks up a value with a tuple. It shows that equal tuples have equal hashes, builds a set in which a duplicate tuple appears only once, and shows the error that occurs when a list is used as a key.
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)

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.

What this code does: It compares tuples with ==, <, 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)]))

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.

What this code does: It defines a 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())
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.

What this code does: It reads four numbers, converts them to floats, and unpacks them into four variables. It stores each point as a tuple, prints both points, uses 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)

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.

What this code does: It reads a line with three comma-separated fields and stores them in a tuple. It unpacks the fields, prints a sentence with the name and the city capitalized, and then builds a new tuple with the age increased by one, because the original tuple cannot be changed.
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))

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] = 1 raises a TypeError, and t.append(1) raises an AttributeError. 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 a ValueError. Match the count, or use a starred variable such as a, *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 call tuple() once at the end.
  • Expecting sorted() to return a tuple: it always returns a list. Wrap it in tuple() 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 are count() and index().
  • Unpacking assigns the items to several variables at once, with * to collect extras and _ for values you ignore.
  • Functions such as divmod(), zip(), enumerate(), and dict.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 namedtuple adds 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.

Ready for the next step?Learn about sets and how to work with unique values.
Next: Sets & Set Operations →