Programming with PythonUnit 58 min read
Strings, Lists, Tuples, Sets, Dictionaries: Python Collections
Unit 5 of Programming with Python covers Python’s built-in data structures—strings (immutable sequences), lists (dynamic arrays), tuples (fixed sequences), sets (unique elements), and dictionaries (key-value pairs)—explaining their syntax, operations, use cases, and performance trade-offs, with real-world examples from
Core Concepts and Definitions
1. Strings: Immutable Sequences of Characters
Strings are ordered, immutable sequences of Unicode characters enclosed in single (') or double (") quotes. They support indexing, slicing, and a rich set of methods.
Key Operations:
- Indexing/Slicing: Access characters via
[i]or extract substrings with[start:stop:step]. - Common Methods:
str.upper(),str.lower(): Case conversion.str.split(delimiter): Split into a list.str.join(iterable): Concatenate with a delimiter.str.replace(old, new): Substitution.str.strip(),str.lstrip(),str.rstrip(): Remove whitespace.
- Formatting: Use f-strings (
f"Hello {name}"),.format(), or%-formatting.
Example: Processing User Input (eSewa-like Validation)
user_input = " user123 "
cleaned = user_input.strip() # Removes leading/trailing spaces
is_valid = cleaned.isalnum() # Checks if alphanumeric
print(f"Valid username: {cleaned}, Status: {'Valid' if is_valid else 'Invalid'}")
Trace:
| Step | user_input |
cleaned |
is_valid |
Output |
|---|---|---|---|---|
| Initial | " user123 " |
– | – | – |
After strip() |
– | "user123" |
– | – |
After isalnum() |
– | – | True |
Valid username: user123, Status: Valid |
2. Lists: Dynamic Arrays
Lists are mutable, ordered collections of items (heterogeneous types allowed) defined with square brackets []. They support indexing, slicing, and in-place modifications.
Key Operations:
- Methods:
list.append(x): Add to end.list.insert(i, x): Insert at indexi.list.remove(x): Remove first occurrence ofx.list.pop([i]): Remove and return item ati(default: last).list.extend(iterable): Add all items from iterable.list.sort(),list.reverse(): In-place sorting/reversing.
- List Comprehensions: Compact syntax for creating lists:
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
Example: Order Queue (Daraz Delivery System)
order_queue = ["Order123", "Order456", "Order789"]
order_queue.append("Order000") # New order arrives
delivered = order_queue.pop(0) # First-come-first-served
print(f"Delivered: {delivered}, Remaining: {order_queue}")
Trace:
3. Tuples: Immutable Sequences
Tuples are ordered, immutable collections defined with parentheses (). They are faster than lists for fixed data and can be used as dictionary keys.
Key Operations:
- Packing/Unpacking:
point = (3, 5) # Packing x, y = point # Unpacking - Methods: Only
count()andindex()(no modifications). - Use Cases: Returning multiple values from functions, heterogeneous fixed data.
Example: Storing Coordinates (Pathao Driver Locations)
driver_locations = [("D1", 27.7172, 85.3240), ("D2", 27.6872, 85.3540)]
for driver_id, lat, lon in driver_locations:
print(f"{driver_id} at ({lat}, {lon})")
Output:
D1 at (27.7172, 85.3240)
D2 at (27.6872, 85.3540)
4. Sets: Unordered Unique Elements
Sets are unordered, mutable collections of unique elements defined with {} or set(). They support mathematical operations like union, intersection, and difference.
Key Operations:
- Methods:
set.add(x): Add an element.set.remove(x): Remove an element (raisesKeyErrorif missing).set.discard(x): Remove if present (no error).set.pop(): Remove and return an arbitrary element.set.clear(): Empty the set.
- Set Operations:
A = {1, 2, 3} B = {3, 4, 5} print(A.union(B)) # {1, 2, 3, 4, 5} print(A.intersection(B)) # {3} print(A.difference(B)) # {1, 2}
Example: Finding Common Users (Khalti and eSewa Overlap)
khalti_users = {"user1", "user2", "user3"}
esewa_users = {"user2", "user3", "user4"}
common_users = khalti_users.intersection(esewa_users)
print(f"Common users: {common_users}")
Trace:
5. Dictionaries: Key-Value Pairs
Dictionaries are mutable, unordered collections of key-value pairs defined with {key: value} syntax. Keys must be immutable (strings, numbers, tuples).
Key Operations:
- Access/Update:
student = {"name": "Rohan", "age": 20} student["grade"] = "A" # Add new key-value print(student["name"]) # Access value - Methods:
dict.keys(),dict.values(),dict.items(): View collections.dict.get(key, default): Safe access (returnsdefaultif key missing).dict.pop(key): Remove and return value.dict.update(other_dict): Merge dictionaries.
- Dictionary Comprehensions:
squares = {x: x**2 for x in range(3)} # {0: 0, 1: 1, 2: 4}
Example: Storing Stock Prices (NEPSE)
stock_prices = {"NTC": 120.50, "Ncell": 850.75, "GlobalIme": 45.20}
stock_prices["NTC"] = 122.00 # Update price
print(f"Updated prices: {stock_prices}")
Trace:
In the Real World
- eSewa/Khalti: Use sets to detect duplicate transactions or dictionaries to map user IDs to transaction histories.
- Daraz: Lists model order queues (FIFO), while dictionaries store product IDs to inventory counts.
- NTC/Ncell: Tuples store (customer_ID, call_duration) for billing, and lists track call logs in chronological order.
Comparison Table: Python Collections
| Feature | String | List | Tuple | Set | Dictionary |
|---|---|---|---|---|---|
| Mutability | Immutable | Mutable | Immutable | Mutable | Mutable |
| Order | Ordered | Ordered | Ordered | Unordered | Unordered (Python 3.7+) |
| Duplicates | No | Allowed | No | No | Keys must be unique |
| Indexing | Yes | Yes | Yes | No | Yes (keys only) |
| Use Case | Text data | Dynamic lists | Fixed data | Unique items | Key-value mappings |
Performance Trade-offs
| Operation | String | List | Tuple | Set | Dictionary |
|---|---|---|---|---|---|
| Access | O(1) | O(1) | O(1) | O(1) | O(1) |
| Search | O(n) | O(n) | O(n) | O(1) | O(1) |
| Insertion | – | O(n) | – | O(1) | O(1) |
| Deletion | – | O(n) | – | O(1) | O(1) |
Note: Sets and dictionaries use hash tables, giving average O(1) for membership tests.
Exam Tip
- Syntax Matters: Memorize the exact syntax for methods like
list.pop(i),set.discard(x), and dictionary unpacking (**kwargs). - Immutability: Strings and tuples cannot be modified after creation—attempting to do so raises
TypeError. - Common Pitfalls:
- Confusing
list.remove(x)(removes firstx) withlist.pop(i)(removes at indexi). - Forgetting that dictionary keys must be immutable (e.g.,
listcannot be a key).
- Confusing
- Real-World Scenarios: Expect questions on modeling scenarios like:
- Bank loans: Use a dictionary to map
account_numbertoloan_amount. - Traffic routes: Use a list of tuples
(source, destination, distance)for Dijkstra’s algorithm.
- Bank loans: Use a dictionary to map
- Code Tracing: Practice tracing operations step-by-step (e.g., how a list changes after
append()orpop()).
Based on the TU BITM syllabus for Programming with Python (IT243), unit 5.
Discussion
Loading…