Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Tuples

A tuple is like a list that cannot change. It holds several values in order and is written with round brackets: (10, 20). Once a tuple is created you cannot add, remove or replace its items. That makes tuples ideal for values that belong together and should stay together: a point with an x and a y, a date, a colour as red, green and blue.

Creating and reading tuples

point = (3, 4)
date = (21, "October", 2026)
single = (5,)          # a tuple of one item needs the comma
print(point[0], point[1])
print(date[1], len(date))
print(type(single), type((5)))
Output
3 4
October 3
<class 'tuple'> <class 'int'>

Indexing, slicing, len, in and for loops work as for lists. Watch out for the tuple with one item: the comma makes the tuple, not the brackets. (5) is just the number 5 in brackets.

Tuples cannot change

point = (3, 4)
point[0] = 10
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    point[0] = 10
    ~~~~~^^^
TypeError: 'tuple' object does not support item assignment

If you need a changed version, make a new tuple, for example point = (10, point[1]). Because they cannot change, tuples can be used as keys in a dictionary and as items of a set, which lists cannot.

Packing and unpacking

Writing values separated by commas packs them into a tuple, and assigning a tuple to several names unpacks it. This is what happens in a, b = b, a:

person = "Asha", 21, "Pune"     # packing: the brackets are optional
name, age, city = person          # unpacking
print(name, "lives in", city)
first, *rest = (1, 2, 3, 4)
print(first, rest)
Output
Asha lives in Pune
1 [2, 3, 4]

A star before a name collects the remaining items into a list.

Returning several values

A function can return a tuple, and the caller unpacks it. This is how Python functions return several results:

def min_max(values):
    return min(values), max(values)

low, high = min_max([7, 2, 9, 4])
print(f"lowest {low}, highest {high}")
Output
lowest 2, highest 9

Practice exercises

  1. Store the RGB values of a colour in a tuple and print each value with a label.
  2. Unpack a tuple of three items into three variables and print them in reverse order.
  3. Write a function that returns the sum and the average of a list, and unpack the result.
  4. Try to append to a tuple and read the error. Then make a new, longer tuple with +.