Skip to content

Tuples

Store fixed values in tuples and unpack them into useful names.

10 min read 10 quiz questions

A tuple is a fixed sequence

A tuple holds ordered values like a list, but you cannot change its items. Tuples usually use parentheses.

For a one-item tuple, the trailing comma is important.

Example 1: create and inspect tuples
point = (3, 5)
one_item = ('hello',)
print(point[1])
print(one_item)
print(point.count(3))
print(point.index(5))

Tuples support indexing and slicing. Their two common methods are count(), which counts a value, and index(), which finds a value's position.

Tuples cannot be changed

Example 2: an immutable tuple
coordinates = (10, 20)
coordinates[0] = 99

Unpack a tuple

Example 3: regular and starred unpacking
person = ('Mina', 14, 'Python')
name, age, subject = person
first, *middle, last = (1, 2, 3, 4)
print(name)
print(age)
print(subject)
print(middle)
print(last)

Unpacking puts tuple values into variables. A starred name such as *middle collects any remaining values into a list.

ChooseWhen it fitsExample
TupleValues should stay fixedA coordinate: (x, y)
ListYou expect to add, remove, or replace itemsA shopping list

Key points

  • Tuples are ordered sequences.
  • A one-item tuple needs a trailing comma.
  • Tuple items cannot be changed.
  • Unpacking assigns tuple values to variables.
  • Use a tuple for fixed data and a list for changing data.

Worked example

GPS coordinates never change in order — the Sundarbans station as an immutable pair.

Example
station = (21.9497, 89.1833)
lat, lon = station
print(lat, lon)

How it works, step by step

  1. (...) makes a tuple: fixed structure, unchangeable contents.
  2. Unpacking copies both fields into named variables in one line.
  3. Trying station[0] = 0 would raise TypeError.

References & Further Reading

Related entries from PyLabs's own reference library.

  • count() (Count the total occurrences of a specific item in a tuple.)
  • index() (Find the zero-based index of the first occurrence of an item.)

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Practice exercise

Not passed yet

Make a tuple city = ('Paris', 'France'). Unpack it into name and country, then print name.

Expected output: Paris

# Write your code below
Want another challenge on this module? More coding practice

Check yourself

Tuples quiz

10 questions. You get instant feedback per question, and the timer starts when you press the button.

Lesson incomplete

Not completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/5 complete
Module cheat sheet