Chapter 38 of 54

Tuples in Python

A list is great when your data keeps changing. But some data should never change once it's created: the days of the week, the coordinates of a point, or a student's roll number and name.

For this kind of fixed data, Python gives us the tuple. A tuple looks and behaves a lot like a list, with one big difference: you cannot change it after it is created.

What is a Tuple?

A tuple is an ordered, immutable collection of items, written with parentheses: (10, 20, 30).

  • Ordered – items keep their position, so you can use indexes.

  • Immutable – you can't add, remove or replace items.

  • Allows duplicates and mixed types – just like a list.

point = (3, 4)
student = ("Asha", 21, "CSE")

print(point)
print(student)
print(type(student))

Output:

(3, 4)
('Asha', 21, 'CSE')
<class 'tuple'>

Creating Tuples

Without Parentheses

Surprisingly, it's the comma that makes a tuple, not the parentheses. This is called tuple packing:

colors = "red", "green", "blue"

print(colors)

Output:

('red', 'green', 'blue')

A Tuple with One Item

This is the most common tuple trap. Parentheses alone don't create a tuple; you need a trailing comma:

not_a_tuple = (5)
a_tuple = (5,)

print(type(not_a_tuple))
print(type(a_tuple))

Output:

<class 'int'>
<class 'tuple'>

Without the comma, Python treats (5) as just the number 5 inside ordinary brackets, like in (2 + 3) * 4.

Empty Tuples and tuple()

empty = ()
from_list = tuple([1, 2, 3])
from_string = tuple("abc")

print(empty)
print(from_list)
print(from_string)

Output:

()
(1, 2, 3)
('a', 'b', 'c')

Accessing Tuple Items

Indexing and slicing work exactly like they do for strings and lists:

days = ("Mon", "Tue", "Wed", "Thu", "Fri")

print(days[0])
print(days[-1])
print(days[1:4])

for day in days:
    print(day, end=" ")

Output:

Mon
Fri
('Tue', 'Wed', 'Thu')
Mon Tue Wed Thu Fri 

Notice that slicing a tuple gives you a new tuple.


Tuples are Immutable

Once a tuple is created, you can't change its items:

point = (3, 4)

point[0] = 10

Output:

TypeError: 'tuple' object does not support item assignment

There is also no append(), remove() or sort() on a tuple. If you really need a "changed" tuple, you create a new one:

point = (3, 4)

point = point + (5,)   # builds a brand-new tuple

print(point)

Output:

(3, 4, 5)

The variable point now refers to a new tuple. The old tuple (3, 4) was never modified.

Immutable Doesn't Mean "Frozen All the Way Down"

A tuple stores references to objects. The tuple can't change which objects it holds, but if one of those objects is mutable (like a list), that object can still change:

data = ("Ravi", [80, 90])

data[1].append(75)

print(data)

Output:

('Ravi', [80, 90, 75])
data ──► ( "Ravi" , ● )
                    │
                    └──► [80, 90, 75]   ← the list itself changed

The tuple still points to the same list. It's the list that changed, not the tuple. This is a popular interview question.


Tuple Methods

Since tuples can't be changed, they have only two methods:

nums = (1, 3, 3, 7, 3)

print(nums.count(3))   # how many times 3 appears
print(nums.index(7))   # position of the first 7

Output:

3
3

Just like with lists, index() raises a ValueError if the value isn't in the tuple.

Other Operations

a = (1, 2)
b = (3, 4)

print(a + b)          # join
print(a * 3)          # repeat
print(2 in a)         # membership
print(len(b), max(b), sum(b))
print(sorted((5, 1, 4)))   # sorted() returns a list

Output:

(1, 2, 3, 4)
(1, 2, 1, 2, 1, 2)
True
2 4 7
[1, 4, 5]

Tuple Unpacking

Unpacking is where tuples really shine. You can pull the items out into separate variables in one line:

student = ("Neha", 20, "IT")

name, age, branch = student

print(name)
print(age)
print(branch)

Output:

Neha
20
IT

The number of variables must match the number of items:

a, b = (1, 2, 3)

Output:

ValueError: too many values to unpack (expected 2, got 3)

(Older Python versions show the same error without the got 3 part.)

Collecting Extra Items with *

Put a * before one variable to collect "everything else" into a list:

marks = (95, 88, 76, 64, 50)

top, *others, lowest = marks

print(top)
print(others)
print(lowest)

Output:

95
[88, 76, 64]
50

Swapping Variables

In many languages, swapping two variables needs a temporary variable. In Python, packing and unpacking do it in one line:

x = 10
y = 20

x, y = y, x

print(x, y)

Output:

20 10

The right side y, x is packed into a tuple (20, 10) first, then unpacked into x and y.

Returning Multiple Values from a Function

When a function "returns multiple values", it actually returns one tuple:

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

result = min_max([4, 9, 1, 7])
print(result)

low, high = min_max([4, 9, 1, 7])
print(low, high)

Output:

(1, 9)
1 9

Unpacking in Loops

enumerate() gives you (index, item) tuples, which you unpack right in the for line:

ranks = [("Asha", 91), ("Ravi", 85)]

for position, (name, score) in enumerate(ranks, start=1):
    print(position, name, score)

Output:

1 Asha 91
2 Ravi 85

Why Use a Tuple Instead of a List?

  • Safety – data that shouldn't change can't be changed by mistake.

  • Meaning – a tuple says "this is a fixed record", like (latitude, longitude).

  • Hashable – a tuple of immutable items can be used as a set element or a dictionary key. A list can't. You'll use this in the next two chapters.

  • Slightly lighter – tuples use a little less memory than lists of the same size, and Python can create constant tuples faster.

Feature

List

Tuple

Syntax

[1, 2, 3]

(1, 2, 3)

Mutable?

Yes

No

Methods

11 (append, sort, ...)

2 (count, index)

Can be a dict key / set item?

No

Yes (if its items are immutable)

Typical use

Collection of similar items that changes

Fixed record of related values

Indexing / len()

O(1)

O(1)

A simple rule: if you'll add or remove items, use a list. If the data is a fixed group of values, use a tuple.


Common Mistakes

  • Forgetting the comma in a single-item tuple: (5) is an int, (5,) is a tuple.

  • Trying to modify a tuple with t[0] = ... or t.append(). Convert it with list(t) if you really need to change it, then back with tuple().

  • Assuming everything inside is frozen. A list inside a tuple can still change.

  • Mismatched unpacking, which raises ValueError. Use *rest when the length can vary.

Final Takeaway

A tuple is an ordered collection that cannot be changed after it's created. It supports indexing, slicing, looping, count() and index(), but none of the methods that modify a list.

Remember: the comma makes the tuple, and unpacking makes tuples a joy to use.

Practice: Write a function that takes a list of numbers and returns a tuple (count, total, average). Unpack the result into three variables and print them.