Python Solution
Python Solution
P a g e 1 | 21
Python Assignment
P a g e 2 | 21
Python Assignment
numbers.insert(2, 3)
print(numbers) # Output: [1, 2, 3, 4]
c) extend() Function
The extend() function adds multiple elements (iterable) to the
end of the list. Unlike append(), which adds a single element,
extend() merges the given iterable.
Syntax:
list.extend(iterable)
Example:
numbers = [1, 2, 3]
numbers.extend([4, 5, 6])
print(numbers) # Output: [1, 2, 3, 4, 5, 6]
These functions enhance list manipulation, making data handling
more efficient in Python.
P a g e 3 | 21
Python Assignment
P a g e 4 | 21
Python Assignment
P a g e 5 | 21
Python Assignment
P a g e 6 | 21
Python Assignment
P a g e 7 | 21
Python Assignment
P a g e 8 | 21
Python Assignment
P a g e 9 | 21
Python Assignment
P a g e 10 | 21
Python Assignment
• Sets are iterable, allowing iteration using loops like for and
while.
• Since sets are unordered, the iteration order is not
guaranteed to match the insertion order.
Thus, sets can be iterated, but the order of elements is
unpredictable.
P a g e 11 | 21
Python Assignment
P a g e 12 | 21
Python Assignment
A.intersection(B)
Example:
A = {1, 2, 3}
B = {3, 4, 5}
print(A & B) # Output: {3}
B = {3, 4, 5}
print(A ^ B) # Output: {1, 2, 4, 5}
Summary:
Operation Symbol Function Result
Union ` ` A.union(B)
Intersection & A.intersection(B) Common
elements in
both sets
Difference - A.difference(B) Elements
in A but
not in B
Symmetric ^ A.symmetric_difference(B) Elements
Difference in either A
or B, but
not both
P a g e 14 | 21
Python Assignment
P a g e 15 | 21
Python Assignment
[] Raises KeyError
P a g e 16 | 21
Python Assignment
P a g e 17 | 21
Python Assignment
P a g e 18 | 21
Python Assignment
P a g e 19 | 21
Python Assignment
student.clear()
print(student) # Output: {}
Key Differences:
Method Removes Returns Raises Error if Key
Value is Missing?
pop(key) Specific key Yes Yes (unless
default provided)
del Specific key No Yes
dict[key]
popitem() Last inserted Yes Yes (if empty)
key (Tuple)
clear() All keys No No
Each method is useful based on the specific removal requirement.
P a g e 20 | 21
Python Assignment
P a g e 21 | 21