10. Tuples
Higher Secondary · Computer Science · Science Stream

Tuples

A tuple is an ordered collection of elements whose key feature is immutability — once created, its values cannot be changed, added, or removed. This chapter covers creating tuples (including packing), indexing and slicing, why immutability matters, concatenation, tuple unpacking and variable swapping, built-in tuple functions, and applications such as currency denomination breakdown and 2D point distance calculation.

10.2 – 10.3 · Live Tool

Tuple Index & Slice Lab

Type a comma-separated tuple and a Python indexing or slicing expression — [2], [-1], [1:4], [-3:], [::-1], [2:7:2] — and watch the ruler highlight exactly which elements get selected.

Try Indexing / Slicing

● live
Enter a comma-separated tuple and an expression like [start:end:step], then press Run.
Try tuple: Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday · expressions: [2:] · [:4] · [-5:-1] · [-2::-2] — highlighted cells show what gets selected; amber numbers are negative indices.
10.1

Creating Tuple

A tuple is created by enclosing its elements within parentheses (), with each element separated by a comma. Its key feature is immutability — once created, its values cannot be changed, added, or removed.

tuple_name = (element1, element2, …) >>>numbers = (10, 20, 30, 40) >>>numbers (10, 20, 30, 40)

A tuple can be created even without parentheses — Python treats a sequence of comma-separated values as a tuple. This is called tuple packing.

>>>hilly_areas = "Munnar", "Ponmudi", "Sholayoor", "Vagamon" >>>print(hilly_areas) ('Munnar', 'Ponmudi', 'Sholayoor', 'Vagamon') # a tuple can hold mixed data types >>>t = ("apple","grapes", 2, 23, 2.5) >>>print(t) ('apple', 'grapes', 2, 23, 2.5)

Single-element tuple needs a comma

A single value inside parentheses without a comma is not a tuple — Python treats it as an ordinary value of that type.

Empty tuple

An empty tuple is created using just a pair of parentheses: t3 = ().

>>>t1 = (1984,) >>>print(t1) (1984,) >>>type(t1) <class 'tuple'> >>>t2 = (78) >>>type(t2) <class 'int'> >>>t3 = ()

Tuples do not have all the methods that lists have — for example, append() does not work with tuples because they are immutable. It is very similar to a list, except for its immutability, which makes tuples ideal for storing fixed sets of information such as geographical coordinates or dates.

10.2

Accessing Tuple Elements

Every element in a tuple has a specific position called its index. Indexing always begins at 0 for the first element — accessing elements in tuples works the same way as in lists.

Positive index0123456
daysMonTueWedThuFriSatSun
Negative index-7-6-5-4-3-2-1
>>>marks = (85, 90, 78, 92) >>>print(marks[0]) 85 >>>print(marks[3]) 92 >>>marks[4] Traceback (most recent call last): IndexError: tuple index out of range # Negative indexing >>>days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") >>>print(days[-1]) Sunday >>>print(days[-3]) Friday

Trying to access an index that does not exist raises an IndexError. Negative indexing is very useful when we want to access elements from the end without calculating their exact positions.

10.3

Slicing a Tuple

When more than one element is needed, a specific portion of the tuple can be extracted using slicing: tuple_name[start:end]. If start is not specified, Python assumes 0; if end is not specified, the slice extends to the end of the tuple.

>>>step_value = (5,10,15,20,25,30,35,40) >>>step_value[1:4] (10, 15, 20) >>>step_value[:4] (5, 10, 15, 20) >>>step_value[4:] (25, 30, 35, 40) >>>step_value[2:-2] (15, 20, 25, 30) >>>step_value[-5:-1] (20, 25, 30, 35)

Slicing with Step Value

start

The index where the slice begins. If omitted, the slice begins from the start of the tuple.

end

The index where the slice stops (this element is not included). If omitted, the slice continues to the end of the tuple.

step

How many positions Python skips after selecting each element. The rules are the same as those used for strings; a negative step accesses elements in reverse order.

ExpressionResultWhat it does
step_value[::2](5, 15, 25, 35)Selects every second element from the beginning.
step_value[1::2](10, 20, 30, 40)Starts from index 1 and takes every second element.
step_value[2:7:3](15, 30)Starts at index 2, ends before index 7, steps by 3.
step_value[::-1](40, 35, 30, 25, 20, 15, 10, 5)Reverses the entire tuple (step is negative).
step_value[-2::-2](35, 25, 15, 5)Starts from second last index and goes back by 2 steps.
10.4

Immutability of Tuple

Like any other literal collection, tuples are objects stored in memory, and variable names are simply references (labels) that point to these objects. Because tuples are immutable, even when two variables point to the same object, we cannot modify its elements.

>>>T1 = (10, 20, 30) >>>T2 = T1 # T2 refers to the SAME tuple object as T1
>>>T1 = (10,20,30) >>>T1[0] = 99 Traceback (most recent call last): TypeError: 'tuple' object does not support item assignment

Attempting to overwrite an existing element with a new value raises a TypeError. This means we can only create a new tuple, but never change an existing one — this is what "immutable" means in practice.

10.5

Concatenation of Tuples & Tuple Unpacking

Concatenation joins two or more tuples into a single tuple using the + operator. Tuple unpacking is the reverse of packing — taking the values inside a tuple and assigning them to separate variables in a single statement.

>>>T1 = (10,20,30) >>>T2 = T1+(40,) >>>print(T2) (10, 20, 30, 40) >>>early_philosophers = ("Socrates", "Plato", "Aristotle") >>>later_philosophers = ("Epicurus","Plotinus","Proclus") >>>all_philosophers = early_philosophers + later_philosophers >>>all_philosophers ('Socrates', 'Plato', 'Aristotle', 'Epicurus', 'Plotinus', 'Proclus')

Python creates a new tuple in memory containing all the elements of T1 along with the new element — T1 itself is never modified, and T2 refers to this new object.

Tuple Unpacking

>>>t = (10, 20, 30) >>>a, b, c = t >>>print(a,b,c) 10 20 30

The statement a, b, c = t unpacks the tuple: the first value is assigned to a, the second to b, and the third to c. Tuple packing and unpacking are particularly useful in functions for handling variable-length arguments and returning multiple results.

Tuple Assignment (Swapping Variables)

# Traditional method — needs a temporary variable temp = a a = b b = temp # Tuple assignment — swap in a single line >>>a=5 >>>b=10 >>>print(f"Before swap: a={a}, b={b}") Before swap: a=5, b=10 >>>a, b = b, a >>>print(f"After swap: a={a}, b={b}") After swap: a=10, b=5

Tuple assignment (sequence unpacking) swaps values by packing them into a tuple and then unpacking them in reverse order — no temporary variable needed.

Conversions: List ↔ Tuple, and Tuples Holding Mutable Members

# List to Tuple >>>my_list = [1,2, 3] >>>my_tuple = tuple(my_list) >>>print(my_tuple) (1, 2, 3) # Tuple to List >>>my_tuple = (4,5,6) >>>my_list = list(my_tuple) >>>print(my_list) [4, 5, 6]

A tuple can hold any type of data, including lists. Even though the tuple itself is immutable, a list inside it can still be changed — because the tuple only fixes which objects it references, not whether those objects are themselves mutable.

cart_data = ("Shadul", "1324.50", ["Shirt", "Cap", "Book"]) cart_data[2].append("Headphone") Cart before adding : ('Shadul', '1324.50', ['Shirt', 'Cap', 'Book']) Items after update: ['Shirt', 'Cap', 'Book', 'Headphone'] Updated cart: ('Shadul', '1324.50', ['Shirt', 'Cap', 'Book', 'Headphone'])
10.6 · Live Tool

Tuple Functions and Operations

Tuples have only two built-in methods of their own — count() and index() — but many of Python's general built-in functions can still be used on tuples. They also support the membership operators in and not in.

Membership Operators — in / not in

>>>numbers = (10, 20, 30, 40, 50) >>>print(20 in numbers) True >>>print(100 in numbers) False >>>weekdays = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri') >>>day = 'Sun' >>>if day not in weekdays: print("It is a weekend") It is a weekend

A tuple can hold another tuple; these are called nested tuples. When tuples are nested, the in operator tests membership against each whole sub-tuple, not the individual items inside it.

>>>total_score = ((20, 40, 60),(18, 39, 45),(17, 34, 40)) >>>print((20, 40, 60) in total_score) True >>>print(40 in total_score) False

Try a Tuple Function

● live
Pick a function, fill in the base tuple and argument (if needed), then press Run.
count()/index() need one value to look for · len()/max()/min()/sum()/all() need no argument (the argument box is hidden for these).
FunctionDescriptionExample
count()Finds out how many times a value appears in the tuplemarks.count(90)
index()Finds the first position where a value appearsai_words.index("Chatbot")
len()Returns the number of elementslen(items)
max()Returns the largest element (numeric or alphabetical)max(marks)
min()Returns the smallest elementmin(marks)
sum()Returns the sum of elements (if numeric)sum(marks)
all()Returns True if all elements are truthy (False, 0, or empty makes it False)all(marks)
10.7

Tuple Applications

In many applications, certain pieces of data must remain unchanged once created — for example, a student's admission record such as (ID, Name, Class). A tuple is ideal for representing such fixed, structured information.

10.7.1 Currency Denomination Analyser

Given an amount, break it down into fixed currency denominations (500, 200, 100, 50, 20, 10) and report how many notes of each are needed, plus simple statistics. The fixed denominations are stored in a tuple because they never change; the calculated counts go into a list because they need to be built up and filtered.

def denomination_generator(amount): denominations = (500, 200, 100, 50, 20, 10) # fixed tuple note_counts = [] # list for counts for d in denominations: count = amount // d amount = amount % d note_counts.append(count) if count > 0: print(f"{d} x {count}") non_zero_counts = [c for c in note_counts if c > 0] print("Total types of notes used:", len(non_zero_counts)) print("Max notes of a single denomination:", max(non_zero_counts)) print("Total number of notes:", sum(non_zero_counts)) Enter the amount: 24190 Breakdown: 500 x 48 100 x 1 50 x 1 20 x 2 Statistics: Total types of notes used: 4 Max notes of a single denomination: 48 Total number of notes: 52

10.7.2 2D Point Distance Calculation

Since a point in 2D space always has exactly two fixed values (x, y) that should not change accidentally, each point is naturally represented as a tuple (x, y). The Euclidean distance between two points is:

d = √( (x2 − x1)² + (y2 − y1)² )
import math def read_points(): x = float(input("x: ")) y = float(input("y: ")) return (x, y) def distance(p1, p2): return math.sqrt((p2[0]-p1[0])**2 + (p2[1]-p1[1])**2) pt1 = read_points() # e.g. (-4.0, 3.0) pt2 = read_points() # e.g. (4.0, -5.0) d = distance(pt1, pt2) print(f"Distance between {pt1} and {pt2}:", d) Distance between (-4.0, 3.0) and (4.0, -5.0): 11.313708498984761

read_points() reads x and y and returns them packed as a tuple; distance(p1, p2) takes two tuples and returns the Euclidean distance between them — a clean example of tuples used purely as fixed, read-only structured data.

Let Us Do

Quick Recap

Tap a question to reveal the answer.

What is the difference between x = (10) and y = (10,)?

type(x) is <class 'int'> because parentheses without a comma are just grouping, not a tuple. type(y) is <class 'tuple'> — the trailing comma is what makes it a single-element tuple.

For A = (10, 20, 30, 40, 50), what does A[-1], A[2:4] give?

50 (30, 40) — A[-1] is the last element, and A[2:4] selects indices 2 and 3 (30 and 40), stopping before index 4.

Why does attempting T1[0] = 99 raise a TypeError?

Because tuples are immutable — once created, Python does not allow item assignment on a tuple object. We can only build a new tuple, never modify the existing one in place.

If T2 = T1 + (40,), does this change T1?

No. Concatenation with + always creates a brand-new tuple object containing the combined elements. T1 still points to its original tuple, while T2 points to the new one.

How does tuple assignment let you swap two variables without a temporary variable?

a, b = b, a first packs the right-hand values (b, a) into a tuple, then unpacks them into a and b in that order — achieving the swap in a single line.

Can a tuple contain a list, and can that list be modified?

Yes. A tuple can hold any data type, including a list. The tuple itself stays immutable (you can't replace which object it references), but a mutable object stored inside it — such as a list — can still be changed in place using methods like append().

For total_score = ((20,40,60),(18,39,45),(17,34,40)), why does 40 in total_score return False?

Because total_score is a nested tuple — the in operator checks whether 40 is itself one of the top-level elements (which are whole sub-tuples), not whether 40 appears somewhere inside one of them.

Which two methods belong to tuples themselves, and what does each do?

count(value) returns how many times a value appears in the tuple; index(value) returns the position of the first occurrence of that value.

Why are tuples used for the fixed currency denominations in the Denomination Analyser, but a list is used for the note counts?

The denominations (500, 200, 100, 50, 20, 10) never change during the program, so a tuple protects them from accidental modification. The note counts, however, are calculated and filtered as the program runs, which requires a mutable structure — a list.

Why is a point in 2D space naturally represented as a tuple (x, y) rather than a list?

A point always has exactly two fixed values that should not be accidentally changed once read — immutability makes a tuple the more appropriate and safer choice for such fixed-size structured data.