Programming with PythonUnit 59 min read
Strings, Lists, Tuples, Sets, Dictionaries: Operations, Traversal & Use Cases
Unit 5 of Programming with Python covers Python’s core data structures—strings, lists, tuples, sets, and dictionaries—explaining their syntax, operations, traversal methods, and real-world applications in apps like eSewa, Daraz, and Ncell. Includes visual step-by-step traces of operations (e.g., sorting a list, hashing
Core Concepts: Strings
Definition & Properties
A string is an immutable sequence of Unicode characters enclosed in single (') or double (") quotes. It supports indexing, slicing, and built-in methods.
text = "Python"
print(text[0]) # 'P' (indexing)
print(text[1:4]) # 'yth' (slicing)
Key Operations:
| Operation | Example | Output |
|---|---|---|
| Concatenation | "Hello" + "World" |
"HelloWorld" |
| Repetition | "Hi" * 3 |
"HiHiHi" |
| Membership | "a" in "apple" |
True |
| Length | len("apple") |
5 |
Visual: String Indexing
String Methods
s = " Hello, World! "
print(s.strip()) # "Hello, World!" (removes whitespace)
print(s.upper()) # " HELLO, WORLD! "
print(s.split(",")) # [" Hello", " World! "]
Example: Cleaning User Input
user_input = " nepal@123 "
cleaned = user_input.strip().lower()
print(cleaned) # "nepal@123"
Trace:
| Step | Action | Result |
|---|---|---|
| 1 | strip() |
"nepal@123" |
| 2 | .lower() |
"nepal@123" |
Lists: Mutable Sequences
Definition & Syntax
A list is a mutable, ordered collection of items (heterogeneous types allowed). Defined with square brackets [].
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange" # Modifies list in-place
Key Operations:
| Operation | Example | Output |
|---|---|---|
| Append | fruits.append("mango") |
["apple", "orange", "cherry", "mango"] |
| Insert | fruits.insert(1, "kiwi") |
["apple", "kiwi", "orange", "cherry"] |
| Remove | fruits.remove("banana") |
Error (not found) |
| Pop | fruits.pop(0) |
"apple" (removes first item) |
Visual: List Insertion
flowchart LR
A["Initial: [apple, banana, cherry]"] -->|"insert('kiwi', 1)"| B["After: [apple, kiwi, banana, cherry]"]List Methods vs. Built-ins
| Method | Built-in Equivalent | Example |
|---|---|---|
append(x) |
list += [x] |
fruits += ["mango"] |
extend(iter) |
list += iter |
fruits += ["grape", "pear"] |
sort() |
sorted(list) |
sorted(fruits) (returns new list) |
Example: Daraz Order Queue
orders = ["Order123", "Order456", "Order789"]
orders.append("Order101") # New order added to end
print(orders) # ["Order123", "Order456", "Order789", "Order101"]
Trace:
| Step | Action | State After Step |
|---|---|---|
| 1 | append("Order101") |
["Order123", "Order456", "Order789", "Order101"] |
Tuples: Immutable Sequences
Definition & Syntax
A tuple is an immutable, ordered collection defined with parentheses (). Used for fixed data (e.g., coordinates, database records).
point = (3, 5) # Immutable: point[0] = 10 → Error
Key Operations:
| Operation | Example | Output |
|---|---|---|
| Indexing | point[0] |
3 |
| Concatenation | (1, 2) + (3,) |
(1, 2, 3) |
| Membership | 4 in (1, 2, 3) |
False |
Visual: Tuple vs. List
classDiagram
class List {
+mutable
+ordered
+[] brackets
}
class Tuple {
+immutable
+ordered
+() parentheses
}
List --> "Inherits from" Sequence
Tuple --> "Inherits from" SequenceExample: NEPSE Stock Prices
stock = ("NTC", 120.50, "2023-10-01")
print(stock[1]) # 120.50 (price)
Trace:
| Step | Action | Output |
|---|---|---|
| 1 | stock[1] |
120.50 |
Sets: Unordered, Unique Elements
Definition & Syntax
A set is an unordered, mutable collection of unique elements. Defined with curly braces {} or set().
unique_numbers = {1, 2, 3, 3, 4} # {1, 2, 3, 4} (duplicates removed)
Key Operations:
| Operation | Example | Output |
|---|---|---|
| Union | `{1, 2} | {2, 3}` |
| Intersection | {1, 2} & {2, 3} |
{2} |
| Difference | {1, 2} - {2, 3} |
{1} |
| Symmetric Diff | {1, 2} ^ {2, 3} |
{1, 3} |
Visual: Set Operations
pie
title Set Operations
"Union (|)" : 3
"Intersection (&)" : 1
"Difference (-)" : 2Example: eSewa Transaction IDs
tx_ids = {"TX101", "TX102", "TX101"} # {"TX101", "TX102"}
tx_ids.add("TX103") # Adds unique ID
print(tx_ids) # {"TX101", "TX102", "TX103"}
Trace:
| Step | Action | State After Step |
|---|---|---|
| 1 | add("TX103") |
{"TX101", "TX102", "TX103"} |
Dictionaries: Key-Value Pairs
Definition & Syntax
A dictionary is a mutable, unordered collection of key-value pairs. Keys must be immutable (strings, numbers, tuples).
student = {"name": "Rama", "age": 20, "courses": ["Math", "CS"]}
print(student["name"]) # "Rama"
Key Operations:
| Operation | Example | Output |
|---|---|---|
| Access | student["age"] |
20 |
| Add/Update | student["grade"] = "A" |
{"name": "Rama", "age": 20, "grade": "A"} |
| Delete | del student["age"] |
Removes key |
| Keys/Values | student.keys() |
dict_keys(["name", "age"]) |
Visual: Dictionary Hashing
graph TD
A["Key: 'name'"] -->|"Hash"| B["Hash Value: 12345"]
B --> C["Index in Table: 12345 % 1000 = 235"]
C --> D["Value: 'Rama'"]Example: Ncell Customer Data
customers = {"CUST101": {"name": "Hari", "balance": 5000},
"CUST102": {"name": "Sita", "balance": 3000}}
customers["CUST101"]["balance"] += 1000 # Top-up
print(customers["CUST101"]["balance"]) # 6000
Trace:
| Step | Action | State After Step |
|---|---|---|
| 1 | customers["CUST101"]["balance"] += 1000 |
{"CUST101": {"name": "Hari", "balance": 6000}} |
In the Real World
eSewa Transactions
- Data Structure Used: Dictionary
- How: Stores user IDs (
"USER123") as keys and transaction details ({"amount": 500, "status": "completed"}) as values. Fast lookup for transaction history.
Daraz Order Processing
- Data Structure Used: List + Queue (FIFO)
- How: Orders are appended to a list (
orders.append("Order123")), and processed in FIFO order usingorders.pop(0)for the oldest order.
Ncell Customer Database
- Data Structure Used: Dictionary of Dictionaries
- How: Outer dictionary keys are phone numbers (
"98XXXXXXXX"), and values are nested dictionaries with{"name": "Ramesh", "balance": 2000}for quick balance checks.
Pathao Driver Routing
- Data Structure Used: Set for Unique Locations
- How: Avoids duplicate pickup/drop locations by storing them in a set (
locations = {"KTM", "Lalitpur", "Bhaktapur"}).
Bank Loan Interest Calculation
- Data Structure Used: Tuple for Fixed Loan Terms
- How: Loan terms
(principal, rate, years)are stored as tuples to ensure immutability during calculations.
Exam Tip
- String Methods: Memorize
strip(),split(),join(), andreplace(). Often tested in input validation questions. - List vs. Tuple: Always check mutability. Lists allow modifications; tuples do not. Example:
def process_data(data): data.append(10) # Works for lists, fails for tuples - Set Operations: Practice union (
|), intersection (&), and difference (-) with concrete examples (e.g., overlapping user groups). - Dictionary Traversal: Know how to loop through keys, values, and items:
for key, value in student.items(): print(f"{key}: {value}") - Common Pitfalls:
- Key Errors: Always check if a key exists (
if "key" in dict). - Tuple Immutability: Avoid
tuple[0] = 5(TypeError). - List vs. String: Strings are immutable; use lists for dynamic text manipulation.
- Key Errors: Always check if a key exists (
- Time Complexity:
- Lists:
O(n)for search (unless sorted),O(1)for append/pop (end). - Dictionaries:
O(1)average for access/insertion (hash-based). - Sets:
O(1)for membership tests.
- Lists:
Practice Questions for TU/PU Exams:
- Write a Python function to reverse a string without using slicing (
[::-1]). - Given a list of integers, remove duplicates and sort the result. Use a set.
- Create a dictionary to store student grades. Add a function to calculate the average grade.
- Explain why
{"a": 1, "b": 2} == {"b": 2, "a": 1}evaluates toTruein Python. - Trace the execution of
list.pop()on[10, 20, 30]and explain the state after each step.
Based on the TU BIM syllabus for Programming with Python (IT243), unit 5.
Discussion
Loading…