A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list, or even another tuple. Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by commas. Like lists and strings, elements of a tuple can be accessed using zero-based index values.
Tuples can be created with mixed data types, nested lists, or nested tuples. A sequence without parenthesis is also treated as a tuple by default.
>>> tuple1 = (1, 2, 3, 4, 5)
>>> tuple2 = ('Economics', 87, 'Accountancy', 89.6)
>>> tuple3 = (10, 20, 30, [40, 50])
>>> tuple4 = (1, 2, 3, 4, 5, (10, 20))
Critical Rule for Single Element Tuples: If there is only a single element in a tuple, it must be followed by a trailing comma. Otherwise, Python treats it as a regular scalar type (e.g., integer or string).
>>> tuple5 = (20) # Treated as integer
>>> type(tuple5)
<class 'int'>
>>> tuple5 = (20,) # Correct single-element tuple
>>> type(tuple5)
<class 'tuple'>
Elements of a tuple are accessed using zero-based indexing and slicing, similar to lists and strings. Negative indexing is also supported.
>>> tuple1 = (2, 4, 6, 8, 10, 12)
>>> tuple1[0]
2
>>> tuple1[-1]
12
Immutability:
Tuples are
immutable
. Once created, their elements cannot be changed or reassigned. Attempting to do so raises a
TypeError
.
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
However, if a tuple contains a mutable element (like a list ), the contents of that mutable element can be modified in-place.
>>> tuple2 = (1, 2, 3, [8, 9])
>>> tuple2[3][1] = 10
>>> tuple2
(1, 2, 3, [8, 10])
Python supports several operations and built-in functions to manipulate and query tuples efficiently.
+
):
Joins two tuples to create a new tuple. Both operands must be tuples.
*
):
Repeats the elements of a tuple a specified number of \times. One operand must be a tuple, and the other must be an integer.
in
/
not in
):
Checks if an element exists within the tuple, returning a boolean value.
[start:stop:step]
.
>>> t1 = (1, 3, 5)
>>> t2 = (2, 4)
>>> t1 + t2
(1, 3, 5, 2, 4)
>>> t2 * 3
(2, 4, 2, 4, 2, 4)
>>> 3 in t1
True
The following built-in functions are commonly used with tuples:
ValueError
if not found.
Tuple assignment allows a tuple of variables on the left side of an assignment operator to be assigned values from a tuple on the right side. The number of variables must match the number of elements in the tuple.
>>> (num1, num2) = (10, 20)
>>> record = ("Pooja", 40, "CS")
>>> (name, rollNo, subject) = record
A
dictionary
is a mapping data type that stores data as key-value pairs. It is an unordered collection of items enclosed in curly braces
{}
, where each key is separated from its value by a colon (
:
).
Keys in a dictionary must be unique and of an immutable data type (e.g., number, string, or tuple). Values can be of any data type and can be repeated.
>>> dict1 = {} # Empty dictionary
>>> dict2 = dict() # Using built-in function
>>> dict3 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92}
Items are accessed via their keys rather than relative positions or indices. Attempting to access a non-existent key raises a
KeyError
.
>>> dict3['Ram']
89
>>> dict3['Shyam']
KeyError: 'Shyam'
Dictionaries are mutable . You can add new key-value pairs or modify existing ones by direct assignment.
>>> dict3['Meena'] = 78 # Adding a new item
>>> dict3['Suhel'] = 93.5 # Modifying an existing item
Membership Operators:
The
in
and
not in
operators check for the presence of a
key
in the dictionary (not the value).
>>> 'Suhel' in dict3
True
Dictionaries can be traversed using a
for
loop in two primary ways:
Method 1: Iterating over keys directly
for key in dict1:
print(key, ':', dict1[key])
Method 2: Iterating over key-value pairs using
items()
for key, value in dict1.items():
print(key, ':', value)
Python provides several built-in functions and methods to manipulate dictionaries:
None
instead of raising an error.
This section provides formal computer science characterizations of the data structures covered in this chapter.
Technical Concept Characterization Matrix
| Core Computer Science Concept | Technical Definition / Operational State | Structural Parameters & Specifications | Computational Function & System Purpose |
|---|---|---|---|
| Tuple | Immutable ordered sequence of elements. |
Enclosed in
()
; elements separated by commas; supports indexing and slicing.
|
Used to store read-only, heterogeneous data collections securely and perform faster iterations. |
| Dictionary | Mutable mapping of unique keys to arbitrary values. |
Enclosed in
{}
; key-value pairs separated by
:
; keys must be immutable.
|
Used for high-performance associative lookups, database-like records, and structured data representation. |
Technical Profile: Python Tuple (tuple)
(elem1, elem2)
or
tuple(iterable)
. Elements accessed via
t[index]
. Supports concatenation (
+
) and repetition (
*
).
Technical Profile: Python Dictionary (dict)
{key: value}
or
dict()
. Keys must be hashable (immutable). Values accessed via
d[key]
or
d.get(key)
.
KeyError
on missing keys if not handled safely.
Below are socio-technical analyses of key programming problems and system implementations using tuples and dictionaries.
Program 10-1: Nested Tuple Student Records
Create a nested tuple to store student details (roll number, name, marks) and print them in a formatted tabular layout.
Socio-Technical Analysis & Core Systemic Impact: This program demonstrates how nested tuples can act as lightweight, read-only database records. By using a nested structure
st = ((101, "Aman", 98), ...), the system guarantees data integrity (records cannot be accidentally modified). The traversal loop uses double indexingst[i][j]to unpack and format the output cleanly using tab escape characters (\t).
Program 10-6: Employee Salary Directory
Write a program to dynamically input employee names and salaries from the user and store them in a dictionary.
Socio-Technical Analysis & Core Systemic Impact: This program highlights the mutable nature of dictionaries for dynamic data collection. It initializes an empty dictionary
employee = dict()and uses awhileloop to populate it with user-defined keys (employee names) and values (salaries). This structure allows instant lookups and updates, making it highly suitable for payroll and directory management systems.