← Back to Python Course | Chapter 6: Data Structures | Lesson 3 of 12

Python Tuples

A tuple is like a list that is sealed in a box: you can read what is inside but you cannot change it. It is good for things that should stay fixed, like the coordinates of a spot.
Syntax
python
tuple_name = (item1, item2, item3)
tuple_name[index]

What is a Tuple?

A tuple is an ordered collection like a list, but once created its elements can't be reassigned, added, or removed -- that immutability makes tuples usable as dictionary keys and signals to readers that the data shouldn't change, like coordinates (x, y).

Example: What is a Tuple?

python
point = (3, 4)
print(point)

Accessing Tuple Items

Tuples support the exact same square-bracket indexing and slicing as lists, so my_tuple[0] and my_tuple[1:3] work identically -- the only real difference is you can't assign through them afterward.

Example: Accessing Tuple Items

python
point = (3, 4, 5)
print(point[0])  # index like a list
print(point[1:3])  # slice like a list, returns a tuple

Tuple Unpacking

Unpacking lets you write x, y = point to pull a tuple's values into named variables in one line, which is why functions that return multiple values (like divmod()) return them as a tuple you can immediately destructure.

Example: Tuple Unpacking

python
point = (3, 4)
x, y = point  # unpacks the tuple's values into x and y
print(x, y)

Tuple Operations

You can't modify a tuple in place, but + concatenates two tuples into a brand-new one and * repeats a tuple's elements, both producing fresh tuple objects rather than touching the originals.

Example: Tuple Operations

python
a = (1, 2)
b = (3, 4)
print(a + b)  # concatenates into a new tuple
print(a * 2)  # repeats a's elements into a new tuple

Tuple Methods

Because tuples can't grow or shrink, they only need count(value) (how many times a value appears) and index(value) (its first position) -- there's no append or remove to support.

Example: Tuple Methods

python
t = (1, 2, 2, 3)
print(t.count(2))  # how many times 2 appears
print(t.index(3))  # position of the first 3
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing a one-item tuple as (5), which is just the integer 5; a one-item tuple needs a trailing comma, (5,).
  2. Trying to change an item with t[0] = 1, which raises TypeError because tuples are immutable.
  3. Unpacking with the wrong number of names, as in a, b = (1, 2, 3), which raises ValueError: too many values to unpack.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.