Question 1 : Unpack tuple with 5 elements in two variables.
Given Tuple:
Expected Output:
Show Answer
Simple Tuple unpacking approach is used.
my_tuple = (1,2,3,4,5)
x,*y = my_tuple
print("x =",x)
print("y =",y)
Output:
Question 2 : Swap the elements of two tuples.
Given Tuple:
tuple1 = (1,2)
tuple2 = (3,4)
Expected Output:
tuple1 = (3, 4)
tuple2 = (1, 2)
Show Answer
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))
Show Answer
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:
Expected Output:
Show Answer
my_tuple = (1,2,[3,4],5)
my_tuple[2][0] = 6
print(my_tuple)
Output:
Question 5 : Count the number of occurrences of item 4 from the tuple
Given Tuple:
Expected Output:
Show Answer
my_tuple = (1,2,3,4,5,4)
print(my_tuple.count(4))
Output:
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:
Show Answer
Solution:
tup = (1,2,3)
lst = [10,20,30,4,5,6]
lst[0:4] = tup
print(lst)
Output:
Question 7 : Write a program to find the second-largest element from the tuple.
Show Answer
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:
Question 8 : Write a program to check if a tuple contains duplicates.
Show Answer
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
© Copyright 2024 www.logicalpython.com. All rights reserved.
We constantly review Tutorials, references, and examples to avoid errors, but we cannot warrant full correctness
of all content.