Python Tuple Exercise and Solutions


Question 1 : Unpack tuple with 5 elements in two variables.

Given Tuple:

(1,2,3,4,5)

Expected Output:

x = 1
y = [2, 3, 4, 5]

Simple Tuple unpacking approach is used.

my_tuple = (1,2,3,4,5)
x,*y = my_tuple

print("x =",x)
print("y =",y)

Output:

x = 1
y = [2, 3, 4, 5]


Question 2 : Swap the elements of two tuples.

Given Tuple:

tuple1 = (1,2)
tuple2 = (3,4)

Expected Output:

tuple1 = (3, 4)
tuple2 = (1, 2)

A Simple Tuple unpacking approach can be used here.

tuple1 = (1,2)
tuple2 = (3,4)

tuple1, tuple2 = tuple2, tuple1

print("tuple1 =", tuple1)
print("tuple2 =", tuple2)

Output:

tuple1 = (3, 4)
tuple2 = (1, 2)


Question 3 : Sort the nested tuple by the second element

Given Tuple:

my_tuple = ((1, 44),(2, 33),(3, 22), (4, 11))

Expected Output:

((4, 11), (3, 22), (2, 33), (1, 44))

Elements of the nested tuple can be sorted using the sorted() function and the lambda function.

my_tuple = ((1, 44),(2, 33),(3, 22), (4, 11))

print(tuple(sorted(my_tuple, key  = lambda x:x[1])))

Output:

((4, 11), (3, 22), (2, 33), (1, 44))


Question 4 : Modify the given tuple as per the expected output

Given Tuple:

(1,2,[3,4],5)

Expected Output:

(1, 2, [6, 4], 5)

my_tuple = (1,2,[3,4],5)

my_tuple[2][0] = 6

print(my_tuple)

Output:

(1, 2, [6, 4], 5)


Question 5 : Count the number of occurrences of item 4 from the tuple

Given Tuple:

(1,2,3,4,5,4)

Expected Output:

2

my_tuple = (1,2,3,4,5,4)

print(my_tuple.count(4))

Output:

2


Question 6 : Replace the first 3 elements of the list with the elements of the tuple. Tuple contains 3 elements only. Note: Tuple should be used once only.

Given Tuple:

tup = (1,2,3)
lst = [10,20,30,4,5,6]

Expected Output:

lst = [1, 2, 3, 5, 6]

Solution:

tup = (1,2,3)
lst = [10,20,30,4,5,6]

lst[0:4] = tup

print(lst)

Output:

[1, 2, 3, 5, 6]


Question 7 : Write a program to find the second-largest element from the tuple.

Using sorted() function:

t = (1,5,8,7,6,3,4)
max_t = max(t)
length = len(t)
second_max = 0

for i in range(length):
    if second_max < t[i] < max_t:
        second_max = t[i]
        
print(second_max)

Without sorted() function:

t = (1,5,8,7,6,3,4)
sorted_t = sorted(t)
print(sorted_t[-2])

Output:

7

Question 8 : Write a program to check if a tuple contains duplicates.

Solution:

tup = (1,2,3,4,5,1,2)

for i in tup:
    if tup.count(i) > 1:
        print("Tuple contains Duplicates")
        break;
else:
    print("No Duplicates exists in the tuple")

Output:

Tuple contains Duplicates