Experiment No.
:- 05
Aim:
To write Python programs that perform tuple operations :
a) To find the index of an item in a tuple
b) To Find the length of a tuple.
c) To reverse a tuple.
d) To sort a list of tuple by its float element.
T heory:
A tuple in Python is an ordered and immutable data type that can store multiple items in a single variable.
Basic tuple operations include:
• Finding index: using the index() method.
• Finding length: using the len() function.
• Reversing: using slicing [::-1].
• Sorting list of tuples: using the sorted() function with a custom key (e.g., ) for sorting logic.
a ) Program to find the index of an item in a tuple
Program:
elements = tuple(input("Enter tuple elements using space:").split())
print("Tuple:", elements)
tem = input("Enter the item to find index of: ")
i
if item in elements:
index = [Link](item)
print(f"Index of '{item}' is:", index)
else:
print(f"'{item}' not found in tuple.")
Sample Output:
Enter tuple elements using space:10 20 30 40 50
Tuple: ('10', '20', '30', '40', '50')
Enter the item to find index of: 30
Index of '30' is: 2
) Program to find the length of a tuple
b
Program:
my_tuple = tuple(input("Enter tuple elements using space: ").split())
print("Tuple:", elements)
print("Length of tuple is:", len(my_tuple))
S ample Output:
Enter tuple elements using space: apple banana cherry mango
Tuple: ('apple', 'banana', 'cherry', 'mango')
Length of tuple is: 4
c ) Program to reverse a tuple
Program:
elements = tuple(input("Enter tuple elements using space: ").split())
reversed_tuple = elements[::-1]
print("Original Tuple:", elements)
print("Reversed Tuple:", reversed_tuple)
S ample Output:
Enter tuple elements using space: 1 2 3 4 5
Original Tuple: ('1', '2', '3', '4', '5')
Reversed Tuple: ('5', '4', '3', '2', '1')
) Program to sort a list of tuples by its float element
d
Program:
n = int(input("How many items? "))
print("Enter item and value (e.g., item1 15.20): ")
data = []
for _ in range(n):
name, price = input("").split()
[Link]((name, price))
orted_list = sorted(data, key=lambda x: float(x[1]), reverse=True)
s
print("Original list:", data)
print("Sorted list:", sorted_list)
S ample Output:
How many items? 3
Enter item and value (e.g., item1 12.20):
item1 12.20
item2 15.10
item3 24.5
Original list: [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
Sorted list: [('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]
Conclusion:
I n this practical, we learned tuple operations like finding index, length, reversing, and sorting tuples by float values,
improving our understanding of tuple manipulation and data handling in Python.