Unit 2: Python Revision Tour - II (Detailed Notes)
Detailed explanations, examples, and board-style Q&A.; Clean white background — no watermarks
or black highlights.
2.1 Introduction
This unit covers strings, lists, tuples, dictionaries and basic sorting techniques. You will learn not just
syntax but WHY these types behave the way they do.
2.2 Strings in Python
Strings are immutable sequences of characters. Immutability means you cannot change a character
at a specific index; any operation that appears to modify a string actually creates a new string object.
Trying to assign to a character index raises a TypeError because strings are immutable. Use slicing
or build a new string instead.
Example: Item assignment
s = 'hello'
# s[0] = 'H' # ERROR: 'str' object does not support item assignment
s2 = 'H' + s[1:]
print(s2) # Hello
Traverse using for-loop or while-loop. Indexing allowed. Useful for character-level processing.
Traversal examples
for ch in 'Python':
print(ch)
s='Python'
i=0
while i < len(s):
print(i, s[i])
i += 1
Common operators: concatenation (+), repetition (*), membership (in), comparison, indexing and
slicing. '+' and '*' create new strings.
String operators
'ab' + 'cd' # 'abcd'
'hi' * 3 # 'hihihi'
'a' in 'apple' # True
'apple' < 'banana' # True (lexicographic)
Slicing returns a new string. Syntax s[start:end:step]. Negative indices allowed. s[::-1] reverses a
string.
Slicing examples
s = 'ABCDEFG'
print(s[1:4]) # BCD
print(s[:3]) # ABC
print(s[3:]) # DEFG
print(s[::-1]) # GFEDCBA
print(s[::2]) # ACEG
• len(s) — length
• s.lower(), s.upper(), s.title(), s.capitalize()
• s.find(sub) — first index or -1
• s.replace(old, new) — returns new string
• s.split(sep) — returns list of substrings
• sep.join(list) — joins into string
• s.strip() / lstrip() / rstrip() — remove whitespace
• s.count(sub) — occurrences
String functions example
s=' Hello World '\nprint(s.strip())
print(s.replace('World','CBSE'))
print('a,b,c'.split(','))
print('-'.join(['2025','09','03']))
2.3 Lists in Python
Lists are ordered, mutable sequences. They can hold items of different types. Use lists when you
need a changeable sequence.
Create list
L = []
L = [1, 2, 3]
L = [1, 'a', [2,3]]
print(L)
Both are sequences, support indexing and slicing. But strings are immutable sequences of
characters, lists are mutable and can hold any objects.
• Concatenation: +
• Repetition: *
• Membership: in
• Indexing and slicing like strings
• append(x) — add at end
• insert(i, x) — insert at index
• remove(x) — remove first occurrence
• pop(i) — remove and return element at i (default last)
• extend(iterable) — extend list
List manipulation
L=[1,2,3]
L.append(4)
L.insert(1, 10)
L.remove(2)
print(L)
print(L.pop())
L.extend([7,8])
print(L)
Assignment makes a reference; to copy use list.copy(), list(slice), or copy module. Changing a
reference affects both names.
Copy vs Reference
A = [1,2,3]
B = A # reference
C = A.copy() # shallow copy
A.append(4)
print(A) # [1,2,3,4]
print(B) # [1,2,3,4]
print(C) # [1,2,3]
• len(L), max(L), min(L), sum(L)
• L.sort(), sorted(L) — in-place vs return new sorted list
• L.reverse(), reversed(L)
Sorting example
L=[3,1,4,2]
print(sorted(L))
L.sort()
print(L)
2.4 Tuples in Python
Tuples are ordered, immutable sequences. Use them for fixed collections of items; they're slightly
faster and hashable (can be dict keys).
Create tuples
T = (1,2,3)
T2 = (5,) # single element tuple
print(type(T))
Tuples immutable vs lists mutable. Tuples can be used as dictionary keys if they contain immutable
elements.
• Indexing and slicing
• Concatenation and repetition
• Membership and iteration
• len(T), max(T), min(T)
• T.index(value), T.count(value)
2.5 Dictionaries in Python
Dictionaries are unordered (in older versions; insertion-ordered in modern Python), mutable
mappings of keys to values. Keys must be immutable and unique.
Create dict
d = {'name':'Ram', 'marks':85}
print(d)
Access by key using d[key] (raises KeyError) or d.get(key, default) which returns default if missing.
Access dict
d = {'a':1}
print(d['a'])
print(d.get('b', 'NA'))
• Keys are unique and immutable (strings, numbers, tuples)
• Values can be any type
• Fast lookups by key (hash table)
• Add/Update: d[key] = value
• Delete: del d[key] or d.pop(key)
• Merge: d.update(other_dict)
• d.keys(), d.values(), d.items()
• d.get(key), d.pop(key), d.update(other), d.clear()
Dict methods example
d={'x':1,'y':2}
for k,v in d.items():
print(k,v)
print(list(d.keys()))
d.update({'z':3})
print(d)
2.6 Sorting Techniques
Compare adjacent elements and swap if out of order. O(n^2) worst-case. Good for understanding
sorting, but slow in practice.
Bubble sort example
def bubble_sort(arr):
n = len(arr)
for i in range(n-1):
for j in range(n-1-i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [5,2,9,1]
bubble_sort(arr)
print(arr) # [1,2,5,9]
Builds sorted array by inserting elements into the correct position. Also O(n^2) worst-case, but good
for nearly-sorted arrays.
Insertion sort example
def insertion_sort(arr):
for i in range(1,len(arr)):
key = arr[i]
j = i-1
while j >= 0 and arr[j] > key:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
arr = [5,2,9,1]
insertion_sort(arr)
print(arr) # [1,2,5,9]