🏫 Python Tuple Programs Using For Loop
Class XI – CBSE
Program 1: Print all elements of a tuple
t = (10, 20, 30, 40, 50)
for i in t:
print(i)
Output:
10
20
30
40
50
Program 2: Print elements with their index
t = ('A', 'B', 'C', 'D')
for i in range(len(t)):
print("Index", i, ":", t[i])
Output:
Index 0 : A
Index 1 : B
Index 2 : C
Index 3 : D
Program 3: Find the sum of all elements
t = (2, 4, 6, 8, 10)
total = 0
for i in t:
total += i
print("Sum =", total)
Output:
Sum = 30
Program 4: Find maximum and minimum in a tuple
t = (23, 45, 12, 67, 34)
max_val = t[0]
min_val = t[0]
for i in t:
if i > max_val:
max_val = i
if i < min_val:
min_val = i
print("Maximum =", max_val)
print("Minimum =", min_val)
Output:
Maximum = 67
Minimum = 12
Program 5: Count even and odd numbers
t = (1, 2, 3, 4, 5, 6, 7, 8, 9)
even = odd = 0
for i in t:
if i % 2 == 0:
even += 1
else:
odd += 1
print("Even numbers:", even)
print("Odd numbers:", odd)
Output:
Even numbers: 4
Odd numbers: 5
Program 6: Print tuple in reverse order
t = (5, 10, 15, 20)
for i in range(len(t)-1, -1, -1):
print(t[i])
Output:
20
15
10
5
Program 7: Count frequency of an element
t = (2, 4, 6, 4, 2, 4, 8)
num = 4
count = 0
for i in t:
if i == num:
count += 1
print(num, "appears", count, "times")
Output:
4 appears 3 times
Program 8: Concatenate two tuples
t1 = (1, 2, 3)
t2 = (4, 5, 6)
result = ()
for i in t1:
result += (i,)
for j in t2:
result += (j,)
print("Combined tuple:", result)
Output:
Combined tuple: (1, 2, 3, 4, 5, 6)
Program 9: Print only string elements
t = (10, 'apple', 25.5, 'banana', True, 'cherry')
for i in t:
if type(i) == str:
print(i)
Output:
apple
banana
cherry
Program 10: Tuple of squares
t = (1, 2, 3, 4, 5)
sq = ()
for i in t:
sq += (i**2,)
print("Squares:", sq)
Output:
Squares: (1, 4, 9, 16, 25)
Program 11: Convert list to tuple
lst = [10, 20, 30, 40]
t = ()
for i in lst:
t += (i,)
print("Tuple:", t)
Output:
Tuple: (10, 20, 30, 40)
Program 12: Product of all elements
t = (2, 3, 4, 5)
product = 1
for i in t:
product *= i
print("Product =", product)
Output:
Product = 120