Unit 2: Python Data Structures & Simple Algorithms
1) List
● Definition: Ordered, mutable collection of elements.
● Mutable: Can change after creation (add, remove, modify elements).
● Syntax: lst = [1,2,3,4]
Operations & Examples:
lst = [10,20,30]
# Add elements
lst.append(40) # [10,20,30,40]
lst.insert(1,15) # [10,15,20,30,40]
# Remove elements
lst.remove(20) # [10,15,30,40]
x = lst.pop() # removes last element 40
# Access/Update
print(lst[0]) # 10
lst[1] = 25 # [10,25,30]
Properties:
Property Explanation
Ordered Elements maintain insertion order
Mutable Can be modified after creation
Duplicates Allowed
Access Time O(1) for index
Insert/Delete O(n) (except at end for append O(1))
Use Case: Dynamic collections, iterative processing, easy slicing, stack/queue simulation.
2) Tuple
● Definition: Ordered, immutable collection of elements.
● Immutable: Cannot modify after creation. Use for fixed data.
● Syntax: t = (1,2,3)
Operations & Examples:
t = (10,20,30)
# Access
print(t[0]) # 10
# Cannot modify
# t[1] = 25 → Error
# Unpacking
a,b,c = t
Properties:
Property Explanation
Ordered Maintains order
Immutable Cannot modify after creation
Duplicates Allowed
Access Time O(1)
Use Case: Fixed data (coordinates, config settings), dictionary keys (hashable).
3) Dictionary (dict)
● Definition: Unordered collection of key-value pairs.
● Mutable: Can add, update, delete entries.
● Keys: Must be immutable (int, str, tuple), values can be anything.
● Syntax: d = {'apple':3,'banana':2}
Operations & Examples:
d = {'apple':3,'banana':2}
# Access
print(d['apple']) # 3
# Add/Update
d['orange'] = 5 # {'apple':3,'banana':2,'orange':5}
d['apple'] = 10 # update
# Delete
del d['banana'] # {'apple':10,'orange':5}
# Iteration
for key, val in d.items():
print(key,val)
Properties:
Property Explanation
Unordered No guaranteed order (Python 3.7+ maintains insertion order)
Mutable Can change contents
Keys Unique Values can duplicate
Lookup O(1) average, O(n) worst
Insert/Delete O(1) average
Use Case: Fast lookups, counting frequency, mapping relationships.
4) Set
● Definition: Unordered collection of unique elements.
● Mutable: Can add/remove elements.
● Syntax: s = {1,2,3}
Operations & Examples:
s = {1,2,3}
# Add
s.add(4) # {1,2,3,4}
# Remove
s.remove(2) # {1,3,4}
# Membership Test
print(3 in s) # True
# Set operations
a = {1,2,3}
b = {3,4,5}
print(a.union(b)) # {1,2,3,4,5}
print(a.intersection(b)) # {3}
Properties:
Property Explanation
Unordered No order guaranteed
Mutable Can add/remove elements
Unique No duplicates
Lookup O(1) average
Insert/Delete O(1) average
Use Case: Remove duplicates, fast membership testing, set operations (union, intersection,
difference).
# Key Differences Between DS:
DS Ordered Mutable Duplicates Lookup Use Case
List Yes Yes Yes O(n) for Dynamic sequence
search
Tupl Yes No Yes O(n) for Fixed sequence, keys
e search
Dict No (ordered in Yes Keys O(1) Key-value mapping
3.7+) unique
Set No Yes No O(1) Unique collection,
membership
Example: Filter even numbers from file
with open("numbers.txt","r") as f:
nums = [int(x) for x in f.read().split()]
evens = [x for x in nums if x%2==0]
with open("even_numbers.txt","w") as f:
f.write(" ".join(map(str,evens)))
● Time Complexity: O(n)
● Space Complexity: O(n)
Example: Count word frequency
text = "apple banana apple orange apple banana"
freq = {}
for word in text.split():
freq[word] = freq.get(word,0)+1
print(freq) # {'apple':3,'banana':2,'orange':1}
● Time Complexity: O(n)
● Space Complexity: O(n)
Example: Unique words
words = ["apple","banana","apple","orange"]
unique_words = set(words)
print(unique_words) # {'apple','banana','orange'}
Factorial (Recursive & Iterative)
# Iterative
def factorial_iter(n):
result=1
for i in range(2,n+1):
result *= i
return result
# Recursive
def factorial_rec(n):
if n<=1:
return 1
return n*factorial_rec(n-1)
Dry-run factorial(5): 5×4×3×2×1=120
Reverse a String
s = "Python"
rev = s[::-1] # slicing
print(rev) # nohtyP
● Time Complexity: O(n)
● Space Complexity: O(n)
Prime Number Check
def is_prime(n):
if n<=1: return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
● Time Complexity: O(√n)
● Space Complexity: O(1)