Page 524 - ComputerScience_Class_11
P. 524
Program 3: Write a program to find the index of a specific element in a tuple using a function.
Program 3.py
File Edit Format Run Options Window Help
def find_element_index(my_tuple, element_to_find):
for index, element in enumerate(my_tuple):
if element == element_to_find:
return index
return -1
numbers_tuple = (10, 20, 30, 40, 50)
element = 30
index_result = find_element_index(numbers_tuple, element)
if index_result != -1:
print(f"The element {element} is found at index {index_result}.")
else:
print(f"The element {element} is not found in the tuple.")
Output
The element 30 is found at index 2.
Program 4: Write a program to swap the first and last elements of a tuple using a function.
Program 4.py
File Edit Format Run Options Window Help
def swap_first_last(my_tuple):
if len(my_tuple) < 2:
return my_tuple
swapped_tuple = (my_tuple[-1],) + my_tuple[1:-1] + (my_tuple[0],)
return swapped_tuple
numbers_tuple = (10, 20, 30, 40, 50)
swapped_result = swap_first_last(numbers_tuple)
print("Original tuple:", numbers_tuple)
print("Swapped tuple:", swapped_result)
Output
Original tuple: (10, 20, 30, 40, 50)
Swapped tuple: (50, 20, 30, 40, 10)
522 Touchpad Computer Science (Ver. 3.0)-XI

