Python Data Structures: Mastering Lists, Tuples, Dictionaries, and Sets

Python Data Structures: Mastering Lists, Tuples, Dictionaries, and Sets
1. Introduction
In our earlier guides, we worked with fundamental variables holding single values—like an integer roll number or a string name—and explored abstract linear concepts like Stacks and Queues. But in everyday programming, software frequently needs to store and manage groups of related items: an attendance roster of 40 students, a subject score lookup table, or unique registration numbers.
In Python, collections of items are handled through powerful built-in Data Structures.
The four primary built-in data types used to store collections are Lists, Tuples, Dictionaries, and Sets. Knowing which one to use in your script determines how fast your program executes, how clean your code looks, and how easily data can be updated.
2. Visual Sketchnote: Python Collections at a Glance
 ╔══════════════════════════════════════════════════════════════════════════════╗
 ║ PYTHON DATA STRUCTURES SKETCHNOTE ║
 ╚══════════════════════════════════════════════════════════════════════════════╝

  [ 1. LIST: [ ] ] [ 2. TUPLE: ( ) ]
   • Ordered & MUTABLE (Changeable) • Ordered & IMMUTABLE (Locked)
   • Allows duplicate values • Allows duplicate values
   ┌──────────────────────────────┐ ┌──────────────────────────────┐
   │ students = ["Aman", "Priya"] │ │ lab_coords = (25.12, 86.09) │
   │ students.append("Rahul") │ │ lab_coords[0] = 30 <─ ERROR │
   └──────────────────────────────┘ └──────────────────────────────┘

 ────────────────────────────────────────────────────────────────────────────────
  [ 3. DICTIONARY: { Key : Value } ] [ 4. SET: { } ]
   • Key-Value pairs • Unordered collection of UNIQUE items
   • Keys must be unique & immutable • Automatically eliminates duplicates
   ┌──────────────────────────────┐ ┌──────────────────────────────┐
   │ marks = {"101": 85, "102": 92}│ │ roles = {"Admin", "Student"} │
   │ print(marks["101"]) ──► 85 │ │ {1, 2, 2, 3} ──► {1, 2, 3} │
   └──────────────────────────────┘ └──────────────────────────────┘

 ────────────────────────────────────────────────────────────────────────────────
  [ QUICK SELECTION RULE ]
   • Need an ordered sequence you can edit later? ──────────► LIST
   • Need fixed constants that must never be altered? ──────► TUPLE
   • Need fast lookups by ID/name instead of index? ────────► DICTIONARY
   • Need to strip duplicate records or check membership? ──► SET
 ════════════════════════════════════════════════════════════════════════════════

3. Deep Dive into the 4 Python Collections
1. Lists: The Versatile Workhorse
A List is an ordered, mutable sequence of elements enclosed in square brackets [].
 * Ordered: Items preserve their defined position. You can access elements via index numbers starting at 0.
 * Mutable: You can add, replace, sort, or remove items at runtime.
 * Common Methods: .append(), .remove(), .pop(), .sort(), .reverse().
# Working with a student list
it_students = ["Aman", "Priya", "Rahul"]
it_students.append("Anjali") # Appends to the end
it_students[0] = "Aman Kumar" # Modifies index 0

2. Tuples: The Protected Constant
A Tuple is an ordered, immutable collection enclosed in parentheses ().
 * Immutable: Once created, elements cannot be appended, removed, or overwritten. This provides data integrity for constants.
 * Memory Efficient: Tuples consume less memory and run faster than lists.
 * Use Case: Storing GPS coordinates, screen resolutions ((1920, 1080)), or database record keys.
screen_res = (1920, 1080)
# screen_res[0] = 1280 # Raises TypeError: 'tuple' object does not support item assignment

3. Dictionaries: Key-Value Mapping
A Dictionary stores data associatively in key: value pairs enclosed in curly braces {}.
 * Fast Lookups: Instead of searching through every index, you retrieve a value directly using its unique key.
 * Structure: Keys must be immutable (like strings or integers) and unique; values can be any data type.
# Student roll to marks lookup
student_scores = {
    "Roll_101": 88,
    "Roll_102": 95,
    "Roll_103": 72
}
print(student_scores["Roll_102"]) # Outputs: 95

4. Sets: Unique Unordered Elements
A Set is an unordered collection of unique elements enclosed in curly braces {} without key-value mappings.
 * No Duplicates: Any duplicate element added is silently dropped.
 * Mathematical Operations: Supports set union (|), intersection (&), and difference (-).
raw_entries = ["Monitor", "Mouse", "Keyboard", "Mouse", "Monitor"]
unique_hardware = set(raw_entries)
print(unique_hardware) # Outputs: {'Monitor', 'Mouse', 'Keyboard'}

4. Summary Comparison Matrix
| Data Structure | Syntax | Ordered? | Mutable? | Allows Duplicates? | Primary Use Case |
|---|---|---|---|---|---|
| List | [a, b] | Yes | Yes | Yes | General collections, dynamic rosters |
| Tuple | (a, b) | Yes | No | Yes | Fixed constants, immutable records |
| Dictionary | {k: v} | Yes (3.7+) | Yes | Keys: No, Values: Yes | Lookups by ID/name, relational mapping |
| Set | {a, b} | No | Yes | No | Deduplication, membership checking |
5. Hands-on Lab Activity: Building a School ICT Lab Inventory
Students can see all four data structures working harmoniously in a single practical Python script:
# ==========================================================
# ICT Lab Exercise: Hardware Inventory & Score Manager
# ==========================================================

# 1. TUPLE: Fixed configuration constants (Cannot be altered)
LAB_CONFIG = ("ICT Room 1", "Utkramit Madhyamik Vidyalaya", 2026)

# 2. LIST: Dynamic list of enrolled student lab assistants
assistants = ["Rohan", "Sneha", "Kunal"]
assistants.append("Vikram")
assistants.remove("Rohan")

# 3. SET: Ensuring unique hardware devices registered
hardware_types = {"Monitor", "CPU Tower", "Keyboard", "Mouse"}
hardware_types.add("Mouse") # Duplicate entry; automatically ignored!

# 4. DICTIONARY: Workstation inspection log (PC_ID -> Working Condition)
pc_health = {
    "PC-01": "Operational",
    "PC-02": "Operational",
    "PC-03": "Needs RAM Upgrade",
    "PC-04": "Operational"
}

# Add a newly inspected workstation
pc_health["PC-05"] = "Operational"

# Display formatted report
print(f"=== {LAB_CONFIG[0]} - {LAB_CONFIG[1]} ({LAB_CONFIG[2]}) ===")
print("Active Assistants :", ", ".join(assistants))
print("Hardware Monitored:", ", ".join(hardware_types))
print(f"Total Unique Hardware Categories: {len(hardware_types)}")

print("\n--- Workstation Status Audit ---")
for pc, status in pc_health.items():
    print(f"[{pc}] -> Status: {status}")

Lab Verification Steps:
 * Open Python IDLE or the Linux terminal on your lab desktop.
 * Save the code as collections_lab.py and run it (F5).
 * Verify that the set ignored the second "Mouse" entry and that the dictionary allows direct inspection of status values using workstation IDs.
6. Review Questions & Key Answers
Q1: What will happen if you attempt to append an item to an existing Tuple?
 * Answer: Python will raise an AttributeError because Tuples are immutable and do not provide an .append() method or allow modifications after definition.
Q2: How does a Python Dictionary locate data faster than a List for large datasets?
 * Answer: A List requires scanning through indices sequentially (O(n) in the worst case), whereas a Dictionary uses an internal hash table that maps each key directly to its memory location in constant average time (O(1)).
Q3: Which built-in Python data structure should you use if you have an attendance list with repeated names and want to extract only the unique attendees?
 * Answer: A Set (set()), which automatically filters out all duplicate values upon initialization.

Comments

Popular posts from this blog

विद्यार्थियों के लिए संस्कृत का अत्यंत प्रसिद्ध और महत्वपूर्ण श्लोक है।

MS Excel