Computer Science: Class 11 — Chapter 10: Tuples and Dictionaries

10.1 Introduction to Tuples

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.

Creating and Initializing Tuples

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'>
  
Accessing Elements and Immutability

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])
  
10.2 Tuple Operations & Built-in Functions

Python supports several operations and built-in functions to manipulate and query tuples efficiently.

Core Tuple Operations
  • Concatenation ( + ): Joins two tuples to create a new tuple. Both operands must be tuples.
  • Repetition ( * ): Repeats the elements of a tuple a specified number of \times. One operand must be a tuple, and the other must be an integer.
  • Membership ( in / not in ): Checks if an element exists within the tuple, returning a boolean value.
  • Slicing: Extracts a subpart of the tuple using [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
  
Built-in Functions for Tuples

The following built-in functions are commonly used with tuples:

  • len() : Returns the total number of elements in the tuple.
  • tuple() : Creates an empty tuple or converts a sequence (string, list, range) into a tuple.
  • count() : Returns the number of \times a given element appears in the tuple.
  • index() : Returns the index of the first occurrence of a specified element. Raises ValueError if not found.
  • sorted() : Takes elements of the tuple and returns a new sorted list (does not modify the original tuple).
  • min() , max() , sum() : Compute the minimum, maximum, and sum of elements in a numeric tuple.
Tuple Assignment & Unpacking

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
  
10.7 Introduction to Dictionaries

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 ( : ).

Creating and Accessing Dictionaries

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'
  
Mutability and Operations

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
  
Traversing a Dictionary

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)
  
10.11 Dictionary Methods & Built-in Functions

Python provides several built-in functions and methods to manipulate dictionaries:

10.12 Technical Profiles & Characterization Matrices

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)

  • Architecture Layer / Tier: Built-in sequence data type in Python's standard library.
  • Operational Mechanics & Syntax: Created via (elem1, elem2) or tuple(iterable) . Elements accessed via t[index] . Supports concatenation ( + ) and repetition ( * ).
  • System Trade-offs & Failures: Offers faster iteration and lower memory footprint than lists, but lacks dynamic resizing and in-place modification capabilities.

Technical Profile: Python Dictionary (dict)

  • Architecture Layer / Tier: Built-in mapping/associative container type in Python's standard library.
  • Operational Mechanics & Syntax: Created via {key: value} or dict() . Keys must be hashable (immutable). Values accessed via d[key] or d.get(key) .
  • System Trade-offs & Failures: Provides $O(1)$ average-case lookup complexity. However, consumes significantly more memory than sequences due to underlying hash table structures, and raises KeyError on missing keys if not handled safely.
10.13 Case Studies & Practical Implementations

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 indexing st[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 a while loop 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.