Skip to content

Computer Science · Ch 10 — Tuples and Dictionaries

Nested Tuples

10.5

Nested Tuples

A tuple placed inside another tuple is called a nested tuple. Nesting is the natural way to store a table of records: each inner tuple is one record (one row), and the outer tuple holds all the records together.

For example, a single student's record — roll number, name and marks (in percentage) — fits in one tuple. To store the details of many students, we make each student's tuple an element of a bigger tuple.

Program: storing and printing student records in a nested tuple

# Store records of students in a nested tuple and print them
students = ((201, "Isha", 96),
            (202, "Rohan", 91),
            (203, "Tanvi", 84),
            (204, "Vikram", 77))

print("S_No", " Roll_No", " Name", " Marks")
for i in range(0, len(students)):
    print((i + 1), '\t', students[i][0], '\t', students[i][1], '\t', students[i][2])

Output:

S_No  Roll_No  Name    Marks
1     201      Isha    96
2     202      Rohan   91
3     203      Tanvi   84
4     204      Vikram  77

How the program works:

  • students is the outer tuple; each element students[i] is itself a tuple holding one student's record. …