20 Python Programs on Tuples
1. Create and print a tuple
t = (1, 2, 3, 4, 5) print("Tuple:", t)
2. Access tuple elements
t = ("apple", "banana", "cherry") print("First element:", t[0]) print("Last
element:", t[-1])
3. Tuple unpacking
t = (10, 20, 30) a, b, c = t print(a, b, c)
4. Check if element exists in a tuple
t = (5, 10, 15, 20) print(15 in t) print(50 in t)
5. Concatenate tuples
t1 = (1, 2, 3) t2 = (4, 5, 6) t3 = t1 + t2 print("Concatenated tuple:", t3)
6. Repeat elements of a tuple
t = ("Hi",) * 4 print(t)
7. Find length of a tuple
t = (100, 200, 300, 400) print("Length:", len(t))
8. Find maximum and minimum in a tuple
t = (4, 7, 1, 9, 3) print("Max:", max(t)) print("Min:", min(t))
9. Convert list to tuple
lst = [1, 2, 3, 4] t = tuple(lst) print(t)
10. Convert tuple to list
t = (10, 20, 30) lst = list(t) print(lst)
11. Count occurrences of an element
t = (1, 2, 2, 3, 4, 2) print("Count of 2:", [Link](2))
12. Find index of an element
t = ("red", "blue", "green", "blue") print("Index of 'blue':", [Link]("blue"))
13. Nested tuple (tuple inside tuple)
t = (1, (2, 3), (4, 5)) print(t[1][1])
14. Slice a tuple
t = (10, 20, 30, 40, 50) print(t[1:4]) # (20, 30, 40)
15. Sort a tuple (convert to list first)
t = (5, 3, 8, 1, 9) sorted_t = tuple(sorted(t)) print(sorted_t)
16. Tuple with different datatypes
t = (1, "Hello", 3.14, True) print(t)
17. Swap two tuples
t1 = (1, 2) t2 = (3, 4) t1, t2 = t2, t1 print("t1:", t1) print("t2:", t2)
18. Find repeated items in a tuple
t = (1, 2, 3, 2, 4, 1, 5) repeated = [x for x in t if [Link](x) > 1]
print(set(repeated))
19. Tuple comprehension (via generator -> tuple)
t = tuple(x*x for x in range(6)) print(t)
20. Zip tuples together
names = ("John", "Alice", "Bob") scores = (85, 92, 78) zipped = tuple(zip(names,
scores)) print(zipped)