Python Practical: Tuples and Sets Operations
Practical No. 7: Perform Operations on Tuples in Python
Aim:
Write a Python program to perform the following operations on Tuples:
a) Create Tuple
b) Access Tuple
c) Update Tuple
d) Delete Tuple
Theory:
A tuple is an ordered collection of items which is immutable (cannot be modified).
Tuples are defined by parentheses () and can hold mixed data types.
- Create Tuple: Use parentheses to define a tuple, e.g., t = (1, 2, 3)
- Access Tuple: Use indexing or slicing to access elements, e.g., t[0]
- Update Tuple: Tuples are immutable. But we can convert it to a list, update it, and convert back to
a tuple.
- Delete Tuple: Use del to delete the entire tuple from memory.
Program:
# a) Create Tuple
my_tuple = (10, 20, 30, 40, 50)
print("Original Tuple:", my_tuple)
# b) Access Tuple
print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])
# c) Update Tuple
# Tuples are immutable, so convert to list first
temp_list = list(my_tuple)
temp_list[2] = 99
my_tuple = tuple(temp_list)
print("Updated Tuple:", my_tuple)
# d) Delete Tuple
del my_tuple
print("Tuple deleted.")
Output:
Original Tuple: (10, 20, 30, 40, 50)
First element: 10
Last element: 50
Updated Tuple: (10, 20, 99, 40, 50)
Tuple deleted.
Conclusion:
Thus, the Python program successfully demonstrated creation, accessing, updating (via
conversion), and deletion of a tuple.
Practical No. 8: Perform Operations on Sets in Python
Aim:
Write a Python program to perform the following operations on Sets:
a) Create Set
b) Access Set elements
c) Update Set
d) Delete Set
Theory:
A set is an unordered collection of unique elements in Python.
Sets are mutable and defined using curly braces {} or the set() constructor.
- Create Set: Initialize using {} or set(), e.g., s = {1, 2, 3}
- Access Elements: You can loop through the set using a for loop (direct indexing is not possible).
- Update Set: Use methods like add(), update() to modify the set.
- Delete Set: Use remove(), discard(), or clear() to delete elements or del to delete the entire set.
Program:
# a) Create Set
my_set = {100, 200, 300}
print("Original Set:", my_set)
# b) Access Set Elements
print("Accessing elements:")
for item in my_set:
print(item)
# c) Update Set
my_set.add(400) # Adding single element
my_set.update([500, 600]) # Adding multiple elements
print("Updated Set:", my_set)
# d) Delete Set
my_set.remove(200) # Removing specific element
print("After removing 200:", my_set)
my_set.clear() # Removing all elements
print("Set after clear:", my_set)
del my_set # Deleting entire set
print("Set deleted.")
Output:
Original Set: {100, 200, 300}
Accessing elements:
100
200
300
Updated Set: {100, 200, 300, 400, 500, 600}
After removing 200: {100, 300, 400, 500, 600}
Set after clear: set()
Set deleted.
Conclusion:
Thus, the Python program successfully demonstrated how to create, access, update, and delete
elements in a set.