01
Unit 13 · 5 hrs
Strings
Immutable sequence of Unicode characters
Indexing & Slicing
s = "Python" # P y t h o n # 0 1 2 3 4 5 (positive) # -6 -5 -4 -3 -2 -1 (negative) s[0] # 'P' s[-1] # 'n' s[1:4] # 'yth' (start incl, stop excl) s[::-1] # 'nohtyP' (reverse) s[1::2] # 'yhn' (every 2nd from index 1)
Key String Methods
| Method | Returns | Example |
|---|---|---|
upper() / lower() | str | "hi".upper() → "HI" |
strip() / lstrip() / rstrip() | str | " hi ".strip() → "hi" |
split(sep) | list | "a,b".split(',') → ['a','b'] |
join(iterable) | str | ','.join(['a','b']) → 'a,b' |
replace(old, new) | str | "cat".replace('c','b') → 'bat' |
find(sub) | int | "hello".find('l') → 2 (−1 if not found) |
count(sub) | int | "abab".count('ab') → 2 |
startswith() / endswith() | bool | "py".startswith('p') → True |
format() | str | "{} {}".format('hi','world') |
isdigit() / isalpha() | bool | "123".isdigit() → True |
Strings are immutable — methods return NEW strings; original unchanged.
s.upper() doesn't modify s.02
Unit 14 · 4 hrs
Lists
Mutable ordered sequence — most versatile data structure
lst = [10, 20, 30, 40, 50] lst[0] # 10 lst[1:3] # [20, 30] lst[-1] # 50 lst[0] = 99 # mutation: [99, 20, 30, 40, 50]
List Methods
| Method | Effect | Returns |
|---|---|---|
append(x) | Add x to end | None |
extend(iterable) | Add all items from iterable | None |
insert(i, x) | Insert x at index i | None |
remove(x) | Remove first x | None |
pop(i) | Remove & return item at i (default: -1) | item |
index(x) | First index of x | int |
count(x) | Number of occurrences | int |
sort() | Sort in-place | None |
reverse() | Reverse in-place | None |
copy() | Shallow copy | list |
clear() | Remove all items | None |
List Comprehension
# [expression for item in iterable if condition] squares = [x**2 for x in range(10)] evens = [x for x in range(20) if x%2==0] flat = [x for row in matrix for x in row]
03
Unit 15 · 2 hrs
Tuples
Immutable ordered sequence
t = (1, 2, 3, 2) t[0] # 1 t[1:3] # (2, 3) t.count(2) # 2 t.index(3) # 2 # Single-element tuple NEEDS trailing comma x = (5,) # tuple y = (5) # int — NOT a tuple! # Unpacking a, b, c = (1, 2, 3) first, *rest = (1, 2, 3, 4) # first=1, rest=[2,3,4]
| Feature | Tuple | List |
|---|---|---|
| Mutable | ❌ No | ✅ Yes |
| Speed | Faster | Slower |
| As dict key | ✅ Yes (hashable) | ❌ No |
| Methods | count, index only | 11+ methods |
| Use when | Fixed data (coords, RGB) | Dynamic collections |
04
Unit 16 · 3 hrs
Dictionaries
Mutable mapping of key-value pairs (ordered since Python 3.7)
d = {'name': 'Alice', 'age': 25}
d['name'] # 'Alice'
d.get('phone', 'N/A')# 'N/A' (safe, no KeyError)
d['city'] = 'Kochi' # add/update
del d['age'] # delete key
Dict Methods
| Method | Returns |
|---|---|
keys() | dict_keys view of all keys |
values() | dict_values view of all values |
items() | dict_items view of (key,value) tuples |
get(key, default) | value or default (no error) |
pop(key) | Remove and return value |
update(other_dict) | Merge another dict in |
setdefault(k,v) | Return value; set if missing |
clear() | Remove all items |
# Iterating for k, v in d.items(): print(f"{k}: {v}") # Dict comprehension sq = {x: x**2 for x in range(5)}
05
Unit 17 · 1 hr
Sets
Unordered collection of unique elements
s = {1, 2, 3, 2} # {1, 2, 3} — duplicates removed
s.add(4) # {1, 2, 3, 4}
s.discard(10) # no error if not found
s.remove(1) # raises KeyError if not found
# Set operations
a = {1,2,3}; b = {2,3,4}
a | b # union: {1,2,3,4}
a & b # intersection: {2,3}
a - b # difference: {1}
a ^ b # symmetric diff:{1,4}
a <= b # is a subset of b?
Sets use hash tables —
in operator is O(1) vs O(n) for lists. Use sets for fast membership testing and deduplication.FC
Quick Review
Flashcards — Module III
Tap to flip