Python Set MCQ : Set 3

Python Set MCQ

1). What is the output of the following code?

List = [1, 2, 3, 4, 5]
list_set = set(List)
print(“Original list: “, List)
print(“List to set: “, list_set)

a) Original list: [1, 2, 3, 4, 5] List to set: {1, 2, 3, 4, 5}
b) Original list: {1, 2, 3, 4, 5} List to set: [1, 2, 3, 4, 5]
c) Original list: [1, 2, 3, 4, 5] List to set: [1, 2, 3, 4, 5]
d) Original list: {1, 2, 3, 4, 5} List to set: {1, 2, 3, 4, 5}

Correct answer is: a) Original list: [1, 2, 3, 4, 5] List to set: {1, 2, 3, 4, 5}
Explanation: The variable `List` is initialized with the values [1, 2, 3, 4, 5]. The set() function is used to convert the list into a set. The resulting set will contain unique elements from the list. The print statements display the original list and the set obtained from the list.

2). What is the output of the following code?

Set = {1, 2, 3, 4, 5}
set_list = list(Set)
print(“Original set: “, Set)
print(“set to list: “, set_list)

a) Original set: {1, 2, 3, 4, 5} set to list: [1, 2, 3, 4, 5]
b) Original set: {1, 2, 3, 4, 5} set to list: {1, 2, 3, 4, 5}
c) Original set: {1, 2, 3, 4, 5} set to list: (1, 2, 3, 4, 5)
d) Error: NameError: name ‘List’ is not defined

Correct answer is: a) Original set: {1, 2, 3, 4, 5} set to list: [1, 2, 3, 4, 5]
Explanation: The code initializes a set called “Set” with values 1, 2, 3, 4, and 5. It then converts the set into a list using the `list()` function and assigns it to the variable “set_list.” The first `print()` statement outputs the original set, which is {1, 2, 3, 4, 5}. The second `print()` statement outputs the converted list, which is [1, 2, 3, 4, 5].

3). What is the output of the following code?

Set = {10, 23, 45, 66, 96, 83}
print(“Original set1: “, Set)
maximum = 0
for ele in Set:
    if ele > maximum:
        maximum = ele
print(“Maximum value: “, maximum)

a) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 96
b) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 83
c) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 66
d) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 45

Correct answer is: a) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 96
Explanation: The code initializes a variable “maximum” to 0 and iterates through the elements of the set “Set”. It compares each element with the current maximum value and updates “maximum” if a larger element is found. The final value of “maximum” is the maximum value in the set, which is 96.

4). What is the output of the following code?

Set = {10, 23, 45, 66, 96, 83}
print(“Original set1: “, Set)
print(“Minimum value: “, min(Set))

a) Original set1: {10, 23, 45, 66, 96, 83}
Minimum value: 10
b) Original set1: {10, 23, 45, 66, 96, 83}
Minimum value: 96
c) Original set1: {10, 23, 45, 66, 96, 83}
Minimum value: 83
d) Error: min() function cannot be used on sets

Correct answer is: a) Original set1: {10, 23, 45, 66, 96, 83}
Minimum value: 10
Explanation: The code creates a set called “Set” with elements 10, 23, 45, 66, 96, and 83. It then prints the original set using the “print” statement. Finally, it uses the “min” function to find the minimum value in the set, which is 10.

5). What is the output of the following code?

Set = {1, 2, 3, 4, 5}
total = 0
print(“Original set1: “, Set)
for ele in Set:
    total += ele
print(“Total of elements in the set: “, total)

a) Original set1: {1, 2, 3, 4, 5}
Total of elements in the set: 15
b) Original set1: {1, 2, 3, 4, 5}
Total of elements in the set: 10
c) Original set1: {1, 2, 3, 4, 5}
Total of elements in the set: 14
d) Original set1: {1, 2, 3, 4, 5}
Total of elements in the set: 5

Correct answer is: a) Original set1: {1, 2, 3, 4, 5}
Total of elements in the set: 15
Explanation: The code initializes a set named “Set” with elements 1, 2, 3, 4, and 5. It also initializes a variable “total” as 0. The code then enters a loop where it iterates over each element “ele” in the set. Inside the loop, the value of “ele” is added to the “total” using the “+=” operator. After the loop, the code prints the original set and the total of elements in the set. In this case, the sum of elements in the set is 1 + 2 + 3 + 4 + 5 = 15. Therefore, the output is “Original set1: {1, 2, 3, 4, 5}” and “Total of elements in the set: 15.”

6). What is the output of the following code?

Set = {1, 2, 3, 4, 5}
print(“Original set1: “, Set)
total = 0
for ele in Set:
    total += ele
print(“Average of the set: “, total / len(Set))

a) Original set1: {1, 2, 3, 4, 5}
Average of the set: 3.0
b) Original set1: {1, 2, 3, 4, 5}
Average of the set: 3
c) Original set1: {1, 2, 3, 4, 5}
Average of the set: 15/5
d) Original set1: {1, 2, 3, 4, 5}
Average of the set: 2.5

Correct answer is: a) Original set1: {1, 2, 3, 4, 5}
Average of the set: 3.0
Explanation: The code calculates the sum of all elements in the set and divides it by the length of the set to find the average. The sum of 1 + 2 + 3 + 4 + 5 is 15, and the length of the set is 5, so the average is 15/5, which is 3.0. The output shows the original set and the calculated average.

7). What is the output of the following code?

Set = {1, 2, 3, 4, 5}
print(“Original set1: “, Set)
count = 0
for ele in Set:
    if ele % 2 == 0:
        count += 1
if count == len(Set):
    print(“All elements in the set are even”)
else:
    print(“All elements in the set are not even”)

a) All elements in the set are even
b) All elements in the set are not even
c) Original set1: {1, 2, 3, 4, 5}
d) Original set1: {2, 4}

Correct answer is: b) All elements in the set are not even
Explanation: The code initializes a set called “Set” with values {1, 2, 3, 4, 5}. It then iterates over each element in the set using a for loop. Inside the loop, it checks if the element is even (divisible by 2) using the condition `ele % 2 == 0`. If an even element is found, the `count` variable is incremented. After the loop, the code compares the value of `count` with the length of the set using the condition `count == len(Set)`. If the count is equal to the length, it means that all elements in the set are even. However, in this case, since the set contains both odd and even numbers, the condition `count == len(Set)` evaluates to False.

8). What will be the output of the following code?

Set = {1, 2, 3, 4, 5}
print(“Original set1: “, Set)
count = 0
for ele in Set:
    if ele % 2 != 0:
        count += 1
if count == len(Set):
    print(“All elements in the set are odd”)
else:
    print(“All elements in the set are not odd”)

a) Original set1: {1, 2, 3, 4, 5} All elements in the set are not odd
b) Original set1: {1, 2, 3, 4, 5} All elements in the set are odd
c) Original set1: {1, 2, 3, 4, 5}
d) Error: Invalid syntax

Correct answer is: a) Original set1: {1, 2, 3, 4, 5} All elements in the set are not odd
Explanation: The code defines a set named “Set” with the values {1, 2, 3, 4, 5}. It then iterates over each element in the set using a for loop. If an element is not divisible by 2 (i.e., odd), the count variable is incremented. After iterating through all elements, the code checks if the count is equal to the length of the set. If they are equal, it means all elements are odd, and it prints “All elements in the set are odd.” Otherwise, it prints “All elements in the set are not odd.” 

9). What is the output of the following code?

Set = {1, 2, 3, 5}
prime = []

for ele in Set:
    count = 0
    for num in range(2, ele):
        if ele % num == 0:
            count += 1
    if count == 0:
        prime.append(ele)

if len(prime) == len(Set):
    print(“All elements in the set are prime numbers”)
else:
    print(“All elements in the set are not prime numbers”)

a) All elements in the set are prime numbers
b) All elements in the set are not prime numbers
c) The code will raise an error
d) The output cannot be determined

Correct answer is: a) All elements in the set are prime numbers
Explanation: The given code first initializes a set Set containing the elements {1, 2, 3, 5}. It also initializes an empty list prime. Next, the code iterates through each element ele in the set Set. For each element, it checks if there exists any number num between 2 and ele – 1 (exclusive) that divides ele without leaving a remainder. If such a number is found, the variable count is incremented. If the count remains 0 after the inner loop completes, it means the element is a prime number, and it is added to the prime list. After processing all elements in the set, the code checks if the number of prime elements in the prime list is equal to the total number of elements in the set Set. If they are equal, it means all elements in the set are prime numbers, and the corresponding message is printed. Otherwise, it means not all elements are prime numbers, and the appropriate message is printed.

10). What is the output of the following code?

a = {1, 2, 4, 5}
print(“Original set: “, a)
a.clear()
print(a)

a) Original set: {1, 2, 4, 5}
{}
b) Original set: {1, 2, 4, 5}
{1, 2, 4, 5}
c) Original set: {1, 2, 4, 5}
Error
d) Original set: {}
{}

Correct answer is: a) Original set: {1, 2, 4, 5}
{}
Explanation: The code defines a set `a` with elements [1, 2, 4, 5]. It then prints the original set `a`, which outputs `{1, 2, 4, 5}`. After that, the `clear()` method is called on set `a`, which removes all elements from the set. Finally, it prints the set `a` again, which results in an empty set `{}`.

11). What is the output of the following code?

a = {1, 2, 4, 5}
print(“Original set: “, a)
print(“Remove element from set: “, a.pop())
print(a)

a) Original set: {1, 2, 4, 5} Remove element from set: 1 {2, 4, 5}
b) Original set: {1, 2, 4, 5} Remove element from set: 5 {1, 2, 4}
c) Original set: {1, 2, 4, 5} Remove element from set: 2 {1, 4, 5}
d) Original set: {1, 2, 4, 5} Remove element from set: 4 {1, 2, 5}

Correct answer is: a) Original set: {1, 2, 4, 5} Remove element from set: 1 {2, 4, 5}
Explanation: The initial set “a” is defined as {1, 2, 4, 5}. When the pop() method is called on set “a”, it removes and returns an arbitrary element from the set. In this case, the element 1 is removed. Therefore, the output of “print(“Original set: “, a)” displays the original set as {1, 2, 4, 5}. The output of “print(“Remove element from set: “, a.pop())” displays the removed element, which is 1. 

12). What is the output of the following code?

a = {1, 2, 4, 5}
b = {2, 4}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“Difference between two sets using – operator: “, a – b)

a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Difference between two sets using – operator: {1, 5}
b) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Difference between two sets using – operator: {1, 2, 4, 5}
c) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Difference between two sets using – operator: {1, 4, 5}
d) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Difference between two sets using – operator: {2, 4}

Correct answer is: a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Difference between two sets using – operator: {1, 5}
Explanation: The expression `a – b` represents the difference between set `a` and set `b`, which contains the elements present in set `a` but not in set `b`. In this case, the elements 1 and 5 are not present in set `b`, so they are included in the output set.

13). What is the output of the following code?

a = {1, 2, 4, 5}
b = {2, 4}
print(“Original set1: “, a)
print(“Original set2: “, b)
count = 0
for ele in b:
    if ele in a:
        count += 1
if count == len(b):
    print(“True”)
else:
    print(“False”)

a) True
b) False
c) Error
d) None

Correct answer is: a) True
Explanation: The code compares the elements of set `b` with set `a`. If all elements of `b` are found in `a`, the variable `count` will be equal to the length of set `b`. In this case, since all elements of `b` (2 and 4) are present in `a`, the count will be equal to the length of `b` (2). Therefore, the output will be “True”.

14). What will be the output of the following code?

Set = {10, 23, 45, 66, 96, 83}
print(“Original set1: “, Set)
print(“Maximum value: “, max(Set))

a) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 96
b) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 83
c) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 10
d) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 45

Correct answer is: a) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 96
Explanation: The given code defines a set named Set with elements 10, 23, 45, 66, 96, and 83. The print statement outputs the original set as {10, 23, 45, 66, 96, 83}. The max() function is used to find the maximum value from the set, which is 96. 

15). What is the output of the following code?

a = {1,2,4,5}
b = {2,4}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Intersection between two sets using the “&” operator: “,a&b)

a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Intersection between two sets using the “&” operator: {2, 4}
b) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Intersection between two sets using the “&” operator: {1, 2, 4, 5}
c) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Intersection between two sets using the “&” operator: {1, 5}
d) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Intersection between two sets using the “&” operator: {1, 2, 4, 5}

Correct answer is: a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Intersection between two sets using the “&” operator: {2, 4}
Explanation: The “&” operator is used to find the intersection between two sets. In this case, set “a” contains the elements {1, 2, 4, 5} and set “b” contains the elements {2, 4}. The intersection of these two sets is {2, 4}, which is displayed as the output.

16). What is the output of the following code?

a = {1, 2, 4, 5}
b = {7, 8}
c = {6, 10, 0}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“Original set3: “, c)
print(“Union of multiple sets using the | operator: “, a | b | c)

a) Original set1: {1, 2, 4, 5}
Original set2: {7, 8}
Original set3: {6, 10, 0}
Union of multiple sets using the | operator: {0, 1, 2, 4, 5, 6, 7, 8, 10}
b) Original set1: {1, 2, 4, 5}
Original set2: {7, 8}
Original set3: {6, 10, 0}
Union of multiple sets using the | operator: {1, 2, 4, 5, 7, 8, 6, 10, 0}
c) Original set1: {1, 2, 4, 5}
Original set2: {7, 8}
Original set3: {6, 10, 0}
Union of multiple sets using the | operator: {1, 2, 4, 5}
d) Error: Invalid use of the | operator for multiple sets

Correct answer is: b) Original set1: {1, 2, 4, 5}
Original set2: {7, 8}
Original set3: {6, 10, 0}
Union of multiple sets using the | operator: {1, 2, 4, 5, 7, 8, 6, 10, 0}
Explanation: The code initializes three sets: `a`, `b`, and `c`. Then it prints the original sets and performs the union operation using the `|` operator on all three sets. The resulting set contains all the elements from the three sets combined. In this case, the output will be `{1, 2, 4, 5, 7, 8, 6, 10, 0}`.

17). What is the output of the following code?

a = {1, 2, 4, 5}
b = {4, 1}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“Symmetric difference of two sets using the “^” operator: “, a^b)

a) Original set1: {1, 2, 4, 5}, Original set2: {4, 1}, Symmetric difference of two sets using the “^” operator: {2, 5}
b) Original set1: {1, 2, 4, 5}, Original set2: {4, 1}, Symmetric difference of two sets using the “^” operator: {1, 2, 4, 5}
c) Original set1: {1, 2, 4, 5}, Original set2: {4, 1}, Symmetric difference of two sets using the “^” operator: {1, 4}
d) Original set1: {1, 2, 4, 5}, Original set2: {4, 1}, Symmetric difference of two sets using the “^” operator: {1, 2, 4, 5}

Correct answer is: a) Original set1: {1, 2, 4, 5}, Original set2: {4, 1}, Symmetric difference of two sets using the “^” operator: {2, 5}
Explanation: The set a contains elements {1, 2, 4, 5} and set b contains elements {4, 1}. The “^” operator is used to calculate the symmetric difference between two sets, which is the set of elements that are present in either set but not in both. In this case, the symmetric difference of sets a and b is {2, 5}, which is printed as the output.

18). What is the output of the following code?

a = {1, 2, 4, 5}
b = {4, 1}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“A is superset of B: “, a.issuperset(b))

a) Original set1: {1, 2, 4, 5} Original set2: {4, 1} A is superset of B: True
b) Original set1: {1, 2, 4, 5} Original set2: {4, 1} A is superset of B: False
c) Original set1: {1, 2, 4, 5} Original set2: {1, 4} A is superset of B: True
d) Original set1: {4, 1} Original set2: {1, 4} A is superset of B: True

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {4, 1} A is superset of B: True
Explanation: The code initializes two sets, ‘a’ and ‘b’, with some elements. The ‘issuperset()’ method is then used to check if ‘a’ is a superset of ‘b’. In this case, ‘a’ contains all the elements of ‘b’ (1 and 4), making ‘a’ a superset of ‘b’. The output will be “Original set1: {1, 2, 4, 5} Original set2: {4, 1} A is superset of B: True”.

19). What is the output of the following code?

a = {1,2,4,5}
b = {4,1}
print(“Original set1: “,a)
print(“Original set2: “,b)
count = 0
for ele in b:
    if ele in a:
        count += 1
if count == len(b):
    print(“A is superset of B”)
else:
    print(“A is not a superset of B”)

a) A is superset of B
b) A is not a superset of B
c) Original set1: {1, 2, 4, 5} Original set2: {4, 1}
d) Original set1: {1, 2, 4, 5} Original set2: {4, 1} A is superset of B

Correct answer is: a) A is superset of B
Explanation: The code checks if set A is a superset of set B. In this case, set A contains all the elements of set B. Therefore, the output will be “A is superset of B.”

20). Which of the following output will be generated by the provided code?

a = {1,2,4,5}
b = {4,1}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Common elements: “)
for ele in a:
    if ele in b:
        print(ele)

a) Original set1: {1, 2, 4, 5}
Original set2: {4, 1}
Common elements:
1
4
b) Original set1: {1, 2, 4, 5}
Original set2: {4, 1}
Common elements:
1
4
5
c) Original set1: {1, 2, 4, 5}
Original set2: {4, 1}
Common elements:
4
5
d) Original set1: {1, 2, 4, 5}
Original set2: {4, 1}
Common elements:
2
5

Correct answer is: a) Original set1: {1, 2, 4, 5}
Original set2: {4, 1}
Common elements:
1
4
Explanation: The provided code iterates over the elements in set `a` and checks if each element is present in set `b`. If an element is found in both sets, it is printed. In this case, the common elements between set `a` and `b` are 1 and 4.

21). What is the output of the following code?

a = {1, 2, 4, 5}
print(“Original set: “, a)
a.remove(5)
print(“After removing 5 from the given set: “, a)

a) Original set: {1, 2, 4, 5}
After removing 5 from the given set: {1, 2, 4}
b) Original set: {1, 2, 4, 5}
After removing 5 from the given set: {1, 2, 5}
c) Original set: {1, 2, 4, 5}
After removing 5 from the given set: {1, 2, 4, 5}
d) Original set: {1, 2, 4, 5}
After removing 5 from the given set: {1, 2, 4, 5, 6}

Correct answer is: a) Original set: {1, 2, 4, 5}
After removing 5 from the given set: {1, 2, 4}
Explanation: The original set `a` is defined as {1, 2, 4, 5}. When the `remove()` method is called with the argument 5, it removes the element 5 from the set. After removing 5, the set becomes {1, 2, 4}. Therefore, the output will be “Original set: {1, 2, 4, 5}” followed by “After removing 5 from the given set: {1, 2, 4}”.

22). What is the output of the following code?

a = {1, 2, 4, 5}
print(“Original set: “, a)
b = {7, 8, 9}
for ele in b:
    a.add(ele)
print(“New set: “, a)

a) Original set: {1, 2, 4, 5}
New set: {1, 2, 4, 5, 7, 8, 9}
b) Original set: {1, 2, 4, 5}
New set: {7, 8, 9}
c) Original set: {1, 2, 4, 5}
New set: {1, 2, 4, 5}
d) Original set: {7, 8, 9}
New set: {1, 2, 4, 5, 7, 8, 9}

Correct answer is: a) Original set: {1, 2, 4, 5} New set: {1, 2, 4, 5, 7, 8, 9}
Explanation: The original set `a` is initialized with elements 1, 2, 4, and 5. The set `b` is initialized with elements 7, 8, and 9. In the for loop, each element from set `b` is added to set `a` using the `add()` method. After the loop, the elements 7, 8, and 9 are added to set `a`.

Python Set MCQ : Set 2

Python Set MCQ

1). Which method is used to return the minimum element from a set?

a) min()
b) minimum()
c) smallest()
d) get_min()

Correct answer is: a) min()
Explanation: The min() function is used to return the minimum element from a set.

2). Which method is used to calculate the sum of elements in a set?

a) sum()
b) total()
c) calculate_sum()
d) get_sum()

Correct answer is: a) sum()
Explanation: The sum() function is used to calculate the sum of elements in a set.

3). Which method is used to find the union of multiple sets?

a) union()
b) combine()
c) merge()
d) unite()

Correct answer is: a) union()
Explanation: The union() method is used to find the union of multiple sets.

4). Which method is used to find the intersection of multiple sets?

a) intersection()
b) common()
c) intersect()
d) same()

Correct answer is: a) intersection()
Explanation: The intersection() method is used to find the intersection of multiple sets.

5). Which method is used to find the difference between multiple sets?

a) difference()
b) subtract()
c) diff()
d) minus()

Correct answer is: a) difference()
Explanation: The difference() method is used to find the difference between multiple sets.

6). Which method is used to find the symmetric difference between multiple sets?

a) symmetric_difference()
b) symmetric_diff()
c) symmetric()
d) diff_symmetric()

Correct answer is: a) symmetric_difference()
Explanation: The symmetric_difference() method is used to find the symmetric difference between multiple sets.

7). Which method is used to update a set with the union of itself and another set?

a) update()
b) add()
c) append()
d) merge()

Correct answer is: a) update()
Explanation: The update() method is used to update a set with the union of itself and another set.

8). Which method is used to remove an element from a set?

a) remove()
b) delete()
c) discard()
d) pop()

Correct answer is: a) remove()
Explanation: The remove() method is used to remove an element from a set.

9). Which method is used to remove an element from a set without raising an error if the element is not present?

a) remove()
b) delete()
c) discard()
d) pop()

Correct answer is: c) discard()
Explanation: The discard() method removes an element from a set, but if the element is not present, no error is raised.

10). Which method is used to check if two sets are disjoint (have no common elements)?

a) is_disjoint()
b) has_common()
c) check_disjoint()
d) is_empty()

Correct answer is: a) is_disjoint()
Explanation: The is_disjoint() method is used to check if two sets have no common elements.

11). Which method is used to check if a set is a superset of another set?

a) is_superset()
b) is_super()
c) superset()
d) issubset()

Correct answer is: a) is_superset()
Explanation: The is_superset() method is used to check if a set is a superset of another set.

12). Which method is used to check if two sets are equal?

a) is_equal()
b) equal()
c) equals()
d) == operator

Correct answer is: d) == operator
Explanation: The == operator is used to check if two sets are equal.

13). Which method is used to remove and return an arbitrary element from a set?

a) remove()
b) delete()
c) pop()
d) extract()

Correct answer is: c) pop()
Explanation: The pop() method removes and returns an arbitrary element from a set.

14). What is the output of the following code?

a = {1, 2, 3, 5, 6}
print(“Original set: “, a)
a.add(7)
print(“New set: “, a)

a) Original set: {1, 2, 3, 5, 6}, New set: {1, 2, 3, 5, 6}
b) Original set: {1, 2, 3, 5, 6}, New set: {1, 2, 3, 5, 6, 7}
c) Original set: {1, 2, 3, 5, 6}, New set: {7}
d) Original set: {1, 2, 3, 5, 6}, New set: {1, 2, 3, 5, 6, 7, 7}

Correct answer is: b) Original set: {1, 2, 3, 5, 6}, New set: {1, 2, 3, 5, 6, 7}
Explanation: The original set `a` contains the elements {1, 2, 3, 5, 6}. The `add()` method is used to add the element 7 to the set `a`. After adding 7, the new set becomes {1, 2, 3, 5, 6, 7}. Therefore, the output is “Original set: {1, 2, 3, 5, 6}, New set: {1, 2, 3, 5, 6, 7}”.

15). What is the output of the following code?

a = {1, 2, 3, 5, 6}
print(“Original set: “, a)
a.remove(5)
print(“New set: “, a)

a) Original set: {1, 2, 3, 5, 6}
New set: {1, 2, 3, 6}
b) Original set: {1, 2, 3, 5, 6}
New set: {1, 2, 3, 5, 6}
c) Original set: {1, 2, 3, 5, 6}
New set: {1, 2, 3}
d) Original set: {1, 2, 3, 5, 6}
New set: {1, 2, 3, 4, 6}

Correct answer is: a) Original set: {1, 2, 3, 5, 6}
New set: {1, 2, 3, 6}
Explanation: The original set `a` contains the elements 1, 2, 3, 5, and 6. The `remove(5)` method is used to remove the element 5 from the set. After removal, the new set `a` contains the elements 1, 2, and 3. Therefore, the output is “Original set: {1, 2, 3, 5, 6}” and “New set: {1, 2, 3, 6}”.

16). What is the output of the following code?

a = {1, 2, 3, 5, 6}
print(“Original set: “, a)
print(“Length of given set: “, len(a))

a) Original set: {1, 2, 3, 5, 6}; Length of given set: 5
b) Original set: {1, 2, 3, 5, 6}; Length of given set: 6
c) Original set: {1, 2, 3, 5, 6}; Length of given set: 4
d) Original set: {1, 2, 3, 5, 6}; Length of given set: 3

Correct answer is: a) Original set: {1, 2, 3, 5, 6}; Length of given set: 5
Explanation: The set `a` contains the elements 1, 2, 3, 5, and 6. When printing the original set, it will display as `{1, 2, 3, 5, 6}`. The `len(a)` function returns the length of the set, which is 5 in this case.

17). What is the output of the following code?

a = {1,2,3,5,6}
print(“Original set: “,a)
if 5 in a:
    print(“True”)
else:
    print(“False”)

a) Original set: {1, 2, 3, 5, 6}\nTrue
b) Original set: {1, 2, 3, 5, 6}\nFalse
c) Original set: {1, 2, 3, 5, 6}
d) True

Correct answer is: a) Original set: {1, 2, 3, 5, 6}\nTrue
Explanation: The code defines a set “a” with the elements {1, 2, 3, 5, 6}. The print statement displays the original set as “Original set: {1, 2, 3, 5, 6}”. The if statement checks if the number 5 is present in the set. Since 5 is indeed an element of the set, the code block under the if statement executes, which prints “True”. Hence, the output will be “Original set: {1, 2, 3, 5, 6}\nTrue” (where “\n” represents a new line).

18). What is the output of the following code?

a = {1, 2, 4, 5}
b = {7, 8, 9, 1}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“Union of a and b: “, a.union(b))

a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Union of a and b: {1, 2, 4, 5, 7, 8, 9}
b) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Union of a and b: {1, 2, 4, 5}
c) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Union of a and b: {7, 8, 9}
d) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Union of a and b: {1, 7, 2, 4, 5, 8, 9}

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Union of a and b: {1, 2, 4, 5, 7, 8, 9}
Explanation: The code creates two sets, `a` and `b`, with specific elements. The `union()` method is then called on set `a` with `b` as an argument. The `union()` method returns a new set that contains all unique elements from both sets. In this case, the union of `a` and `b` will be {1, 2, 4, 5, 7, 8, 9}, which will be printed as the output.

20). What is the output of the code?

a = {1,2,4,5}
b = {7,8,9,1}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Intersection of a and b: “,a.intersection(b))

a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Intersection of a and b: {1}
b) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Intersection of a and b: {1, 7, 8, 9}
c) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Intersection of a and b: {2, 4, 5}
d) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Intersection of a and b: {7, 8, 9}

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Intersection of a and b: {1}
Explanation: The intersection of sets a and b is the set of elements that are common to both sets. In this case, the intersection is {1}, as 1 is present in both sets a and b. The intersection() method is used to find the intersection of sets. The code correctly prints the original sets and the intersection set.

21). What is the output of the above code?

a = {1,2,4,5}
b = {7,8,9,1}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Difference of a and b: “,a.difference(b))

a) Original set1: {1, 2, 4, 5}
Original set2: {7, 8, 9, 1}
Difference of a and b: {2, 4, 5}
b) Original set1: {1, 2, 4, 5}
Original set2: {7, 8, 9, 1}
Difference of a and b: {1, 2, 4, 5}
c) Original set1: {1, 2, 4, 5}
Original set2: {7, 8, 9, 1}
Difference of a and b: {2, 4, 5}
d) Original set1: {1, 2, 4, 5}
Original set2: {7, 8, 9, 1}
Difference of a and b: {}

Correct answer is: c) Original set1: {1, 2, 4, 5}
Original set2: {7, 8, 9, 1}
Difference of a and b: {2, 4, 5}
Explanation: The difference() method returns a new set containing the elements that are present in set ‘a’ but not in set ‘b’.

22). What is the output of the above code?

a = {1,2,4,5}
b = {7,8,9,1}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Symmetric difference of a and b: “,a.symmetric_difference(b))

a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Symmetric difference of a and b: {2, 4, 5, 7, 8, 9}
b) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Symmetric difference of a and b: {2, 4, 5}
c) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Symmetric difference of a and b: {1, 7, 8, 9}
d) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Symmetric difference of a and b: {1}

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Symmetric difference of a and b: {2, 4, 5, 7, 8, 9}
Explanation: The symmetric_difference() method returns a new set that contains elements present in either set a or set b, but not in both.

Python Set MCQ : Set 1

Python Set MCQ

1). What is a set in Python?

a) A sequence of elements
b) A collection of unordered and unique elements
c) A data structure used for sorting elements
d) A variable that can store multiple values

Correct answer is: b) A collection of unordered and unique elements
Explanation: In Python, a set is an unordered collection of unique elements.

2). Which symbol is used to define a set in Python?

a) []
b) {}
c) ()
d) <>

Correct answer is: b) {}
Explanation: Curly braces {} are used to define a set in Python.

3). What is the result of executing the following code: set = {1, 2, 3}?

a) [1, 2, 3, 4]
b) {1, 2, 3,}
c) {1, 2, 3}
d) {2, 2, 3, 1}

Correct answer is: c) {1, 2, 3}
Explanation: Sets only contain unique elements, so duplicate values are removed.

4). In Python which method is used to add an element to a set?

a) add()
b) insert()
c) append()
d) update()

Correct answer is: a) add()
Explanation: The add() method is used to add a single element to a set.

5). Which method is used to remove an element from a set?

a) remove()
b) delete()
c) discard()
d) pop()

Correct answer is: c) discard()
Explanation: The discard() method removes a specified element from a set.

6). What happens if you use the remove() method to remove an element that doesn’t exist in the set?

a) It raises a KeyError
b) It raises an IndexError
c) It removes the last element in the set
d) It does nothing and doesn’t raise an error

Correct answer is: a) It raises a KeyError
Explanation: The remove() method raises a KeyError if the element doesn’t exist in the set.

7). Which method is used to remove an arbitrary element from a set?

a) remove()
b) delete()
c) discard()
d) pop()

Correct answer is: d) pop()
Explanation: The pop() method removes and returns an arbitrary element from a set.

8). Which method is used to clear all elements from a set?

a) clear()
b) remove()
c) discard()
d) delete()

Correct answer is: a) clear()
Explanation: The clear() method removes all elements from a set, leaving an empty set.

9). Which operator is used to perform the union of two sets?

a) &
b) |
c) –
d) ^

Correct answer is: b) |
Explanation: The | operator is used for the union operation, which combines elements from two sets.

10). Which operator is used to perform the intersection of two sets?

a) &
b) |
c) –
d) ^

Correct answer is: a) &
Explanation: The & operator is used for the intersection operation, which returns common elements from two sets.

11). Which operator is used to perform the difference between two sets?

a) &
b) |
c) –
d) ^

Correct answer is: c) –
Explanation: The – operator is used for the difference operation, which returns elements present in the first set but not in the second set.

12). Which operator is used to perform the symmetric difference between two sets?

a) &
b) |
c) –
d) ^

Correct answer is: d) ^
Explanation: The ^ operator is used for the symmetric difference operation, which returns elements present in either set, but not in both.

13). What is the result of executing the following code: set1 = {1, 2, 3}; set2 = {3, 4, 5}; symmetric_difference_set = set1 ^ set2; print(symmetric_difference_set)?
a) {1, 2, 3, 4, 5}
b) []
c) {1, 2, 4, 5}
d) {1, 2, 3}

Correct answer is: c) {1, 2, 4, 5}
Explanation: The ^ operator returns elements present in either set but not in both, which are 1, 2, 4, and 5.

14). Which method is used to check if a set is a subset of another set?

a) issubset()
b) issuperset()
c) subset()
d) superset()

Correct answer is: a) issubset()
Explanation: The issubset() method checks if a set is a subset of another set.

15). Which method is used to check if a set is a superset of another set?

a) issubset()
b) issuperset()
c) subset()
d) superset()

Correct answer is: b) issuperset()
Explanation: The issuperset() method checks if a set is a superset of another set.

16). Which method is used to check if two sets have no common elements?

a) isdisjoint()
b) iscommon()
c) nocommon()
d) nodisjoint()

Correct answer is: a) isdisjoint()
Explanation: The isdisjoint() method checks if two sets have no common elements.

17). Which method is used to return a shallow copy of a set?

a) copy()
b) clone()
c) duplicate()
d) replicate()

Correct answer is: a) copy()
Explanation: The copy() method in Python returns a shallow copy of a set.

18). Which method is used to return the length of a set?

a) size()
b) length()
c) count()
d) len()

Correct answer is: d) len()
Explanation: The len() function in Python returns the number of elements in a set.

19). Which method is used to convert a list into a set?

a) to_set()
b) set()
c) convert_set()
d) list_to_set()

Correct answer is: b) set()
Explanation: The set() function is used to convert a list into a set.

20). Which method is used to convert a set into a list?

a) to_list()
b) list()
c) convert_list()
d) set_to_list()

Correct answer is: b) list()
Explanation: The list() function is used to convert a set into a list.

21). Which method is used to iterate over the elements of a set?

a) iterate()
b) for loop
c) loop()
d) iterate_elements()

Correct answer is: b) for loop
Explanation: A for loop is used to iterate over the elements of a set.

22). Which method is used to return a frozen set from a set?

a) freeze()
b) frozen_set()
c) freeze_set()
d) frozenset()

Correct answer is: d) frozenset()
Explanation: The frozenset() function is used to return a frozen set from a set.

Python Dictionary MCQ : Set 4

Python Dictionary MCQ

1). What is the output of the following code?

dict1 = {“m1”: 40, “m2”: 50, “m3”: None}
dict2 = {}
for key, val in dict1.items():
    if val != None:
        dict2[key] = val

print(dict2)

a) {“m1”: 40, “m2”: 50}
b) {“m1”: 40, “m2”: 50, “m3”: None}
c) {“m3”: None}
d) {}

Corresct answer is: a) {“m1”: 40, “m2”: 50}
Explanation: The code iterates over the key-value pairs in `dict1` using the `items()` method. It checks if the value is not equal to None and adds the key-value pair to `dict2`. In this case, the value of “m3” is None, so it is excluded from `dict2`. The output will be `{“m1”: 40, “m2”: 50}`, which are the key-value pairs that have a non-None value in `dict1`.

2). What is the output of the following code?

dict1 = {‘alex’: 50, ‘john’: 45, ‘Robert’: 30}
dict2 = {}

for key, val in dict1.items():
    if val > 40:
        dict2[key] = val
print(dict2)

a) {‘alex’: 50, ‘john’: 45}
b) {‘alex’: 50}
c) {‘john’: 45}
d) {}

Corresct answer is: a) {‘alex’: 50, ‘john’: 45}
Explanation: The code iterates over the key-value pairs in dict1 using the items() method. It checks if the value is greater than 40. If the condition is true, it adds the key-value pair to dict2. In this case, both ‘alex’ and ‘john’ have values greater than 40, so they are added to dict2. Therefore, the output is {‘alex’: 50, ‘john’: 45}.

3). What is the output of the following code?

dict1 = {‘name’:[‘Apr’,’May’,’June’],’month’:[4, 5, 6]}
res = dict(zip(dict1[‘name’],dict1[‘month’]))
print(res)

a) {‘Apr’: 4, ‘May’: 5, ‘June’: 6}
b) {‘name’: [‘Apr’, ‘May’, ‘June’], ‘month’: [4, 5, 6]}
c) {‘name’: ‘June’, ‘month’: 6}
d) {‘Apr’: [4, 5, 6], ‘May’: [4, 5, 6], ‘June’: [4, 5, 6]}

Corresct answer is: a) {‘Apr’: 4, ‘May’: 5, ‘June’: 6}
Explanation: The code uses the `zip()` function to combine the elements from `dict1[‘name’]` and `dict1[‘month’]` into pairs. The `dict()` function is then used to convert the resulting pairs into a dictionary. The output will be `{‘Apr’: 4, ‘May’: 5, ‘June’: 6}`, where the names are the keys and the corresponding months are the values.

4). What is the output of the following code?

list1 = [(“mike”,1),(“sarah”,20),(“jim”, 16)]
dict1 = {}
for val in list1:
    dict1[val[0]] = val[1]
print(dict1)

a) {‘mike’: 1, ‘sarah’: 20, ‘jim’: 16}
b) {‘mike’: 1, ‘sarah’: 20, ‘jim’: 16, ‘val’: 1, ‘val’: 20, ‘val’: 16}
c) {‘mike’: 1, ‘sarah’: 20, ‘jim’: 16, 0: ‘mike’, 1: ‘sarah’, 2: ‘jim’}
d) Error

Corresct answer is: a) {‘mike’: 1, ‘sarah’: 20, ‘jim’: 16}
Explanation: The code iterates over the list of tuples `list1` and assigns each tuple’s first element as a key and the second element as its corresponding value in the dictionary `dict1`. The resulting dictionary will contain the key-value pairs: {‘mike’: 1, ‘sarah’: 20, ‘jim’: 16}.

5). What is the output of the following code?

str1 = “Apr=April; Mar=March”
dictionary = dict(subString.split(“=”) for subString in str1.split(“;”))
print(dictionary)

a) {‘Apr’: ‘April’, ‘ Mar’: ‘March’}
b) {‘Apr’: ‘April’, ‘Mar’: ‘March’}
c) {‘Apr=April’: ‘Mar=March’}
d) Error

Corresct answer is: b) {‘Apr’: ‘April’, ‘Mar’: ‘March’}
Explanation: The code snippet splits the string `str1` into substrings using the “;” delimiter. It then splits each substring using the “=” delimiter to obtain key-value pairs. These key-value pairs are used to create a dictionary using the `dict()` constructor. The resulting dictionary will have keys ‘Apr’ and ‘Mar’ with corresponding values ‘April’ and ‘March’, respectively. The whitespaces before ‘Mar’ in option (a) are incorrect, and option (c) combines the entire input string as a single key. 

6). What is the output of the following code?

matrix = [[1,2,3],[4,5,6]]
dict1 = {}
for i in range(len(matrix)):
    dict1[i+1] = matrix[i]
print(dict1)

a) {1: [1,2,3], 2: [4,5,6]}
b) {0: [1,2,3], 1: [4,5,6]}
c) {1: [0,1,2], 2: [3,4,5]}
d) {0: [0,1,2], 1: [3,4,5]}

Corresct answer is: a) {1: [1,2,3], 2: [4,5,6]}
Explanation: The code initializes an empty dictionary `dict1` and then iterates over the indices of the `matrix`. For each index `i`, it assigns the value of `matrix[i]` to `dict1[i+1]`. Since the indices start from 0, `i+1` is used to create keys starting from 1. Therefore, the resulting dictionary is `{1: [1,2,3], 2: [4,5,6]}`.

7). What is the output of the following code?

D1 = {‘virat’: 50, ‘rohit’: 50, ‘rahul’: 50, ‘hardik’: 50}
result = all(x == 50 for x in D1.values())
print(result)

a) True
b) False
c) Error
d) None

Corresct answer is: a) True
Explanation: The code initializes a dictionary `D1` with keys `’virat’`, `’rohit’`, `’rahul’`, and `’hardik’`, each having a value of `50`. The expression `all(x == 50 for x in D1.values())` checks if all the values in the dictionary `D1` are equal to `50`. In this case, all the values in `D1` are indeed `50`, so the expression evaluates to `True`.

8). What is the output of the following code?

D1 = [(‘virat’,50), (‘rohit’,40), (‘virat’,30), (‘rohit’,10)]

def grouping_dictionary(l):
    result = {}
    for k, v in l:
        result.setdefault(k, []).append(v)
    return result

print(grouping_dictionary(D1))

a) {‘virat’: [50, 30], ‘rohit’: [40, 10]}
b) {‘virat’: [50, 30], ‘rohit’: [40]}
c) {‘virat’: [50], ‘rohit’: [40, 10]}
d) {‘virat’: [50], ‘rohit’: [40]}

Corresct answer is: a) {‘virat’: [50, 30], ‘rohit’: [40, 10]}
Explanation: The code defines a function `grouping_dictionary()` that takes a list of tuples as input. It iterates over each tuple and uses the `setdefault()` method to create a new key in the `result` dictionary if it doesn’t already exist, and appends the corresponding value to the list associated with that key. In this case, the output will be `{‘virat’: [50, 30], ‘rohit’: [40, 10]}`. The values for the keys ‘virat’ and ‘rohit’ are grouped together as lists.

9). What is the output of the following code?

A = { ‘a’: ’30’, ‘b’: ’20’, ‘c’: ’10’ }
D1 = {}
for k,v in A.items():
    D1[k] = int(v)
print(D1)

a) D1 = {‘a’: 30, ‘b’: 20, ‘c’: 10}
b) D1 = {‘a’: ’30’, ‘b’: ’20’, ‘c’: ’10’}
c) D1 = {‘a’: 3, ‘b’: 2, ‘c’: 1}
d) D1 = {’30’: ‘a’, ’20’: ‘b’, ’10’: ‘c’}

Corresct answer is: a) D1 = {‘a’: 30, ‘b’: 20, ‘c’: 10}
Explanation: The code initializes an empty dictionary `D1`. It then iterates over the items of dictionary `A` using the `items()` method, which provides key-value pairs. In each iteration, it assigns the key to variable `k` and the value to variable `v`. The line `D1[k] = int(v)` assigns the key-value pair to `D1`, where the value is converted to an integer using the `int()` function. Therefore, the resulting `D1` dictionary will have the same keys as `A`, but with the values converted to integers. Thus, the content of `D1` will be {‘a’: 30, ‘b’: 20, ‘c’: 10}.

10). What is the output of the following code?

B = {‘a’: ‘3.33’, ‘b’: ‘20.50’, ‘c’: ‘12.5’}
D2 = {}
for key, val in B.items():
    D2[key] = float(val)
print(D2)

a) {‘a’: ‘3.33’, ‘b’: ‘20.50’, ‘c’: ‘12.5’}
b) {‘a’: 3.33, ‘b’: 20.5, ‘c’: 12.5}
c) {‘a’: ‘3.33’, ‘b’: ‘20.50’, ‘c’: ‘12.5’}
d) {‘a’: ‘3.33’, ‘b’: ‘20.50’, ‘c’: ‘12.5’}

Corresct answer is: b) {‘a’: 3.33, ‘b’: 20.5, ‘c’: 12.5}
Explanation: The code initializes an empty dictionary `D2`. It then iterates through the key-value pairs of dictionary `B` using the `items()` method. For each key-value pair, the code converts the value from string to float using the `float()` function and assigns the converted value to the corresponding key in `D2`. Finally, it prints the contents of `D2`. As a result, the output will be `{‘a’: 3.33, ‘b’: 20.5, ‘c’: 12.5}` where the values are converted to floating-point numbers.

11). What is the output of the following code?

D1 = {‘virat’: [50, 30], ‘rohit’: [40, 10]}
for key in D1:
    D1[key].clear()
print(D1)

a) {}
b) {‘virat’: [], ‘rohit’: []}
c) {‘virat’: None, ‘rohit’: None}
d) Error

Corresct answer is: b) {‘virat’: [], ‘rohit’: []}
Explanation: The given code iterates over each key in the dictionary `D1` using the `for` loop. Inside the loop, the `clear()` method is called on each list value associated with the keys in `D1`. The `clear()` method removes all elements from a list, making it an empty list. After the loop completes, the dictionary `D1` will have empty lists as the values for both ‘virat’ and ‘rohit’ keys. 

12). What will be the output of the given code snippet?

D1 = [{‘t20′:50,’odi’:70},{‘t20′:40,’odi’:10},{‘t20′:30,’odi’:0},{‘t20′:45,’odi’:65}]
l = []

for ele in D1:
    for key,val in ele.items():
        if key == ‘odi’:
            l.append(val)
print(l)

a) [70, 10, 0, 65]
b) [70, 40, 30, 45]
c) [50, 40, 30, 45]
d) [70, 45]

Corresct answer is: a) [70, 10, 0, 65]
Explanation: The code initializes an empty list `l`. It then iterates over each dictionary element `ele` in the list `D1`. For each dictionary, it checks if the key is ‘odi’. If it is, the corresponding value is appended to the list `l`. In this case, the values of ‘odi’ keys in the dictionaries are [70, 10, 0, 65], which results in the output [70, 10, 0, 65].

13). What is the output of the following code?

D1 = {1:’sql’,2:’tools’,3:’python’}
D2 = {}

for val in D1.values():
    D2[val] = len(val)
print(D2)

a) {1: 3, 2: 5, 3: 6}
b) {‘sql’: 3, ‘tools’: 5, ‘python’: 6}
c) {1: ‘sql’, 2: ‘tools’, 3: ‘python’}
d) {‘sql’: 1, ‘tools’: 2, ‘python’: 3}

Corresct answer is: b) {‘sql’: 3, ‘tools’: 5, ‘python’: 6}
Explanation: The code initializes an empty dictionary `D2` and iterates over the values of `D1` using a for loop. For each value `val`, a key-value pair is added to `D2` where the key is `val` and the value is the length of `val`. In this case, the length of ‘sql’ is 3, the length of ‘tools’ is 5, and the length of ‘python’ is 6. 

14). What is the output of the following code?

D1 = {‘sqatools’: 8, ‘python’: 6}
l = [1, 2]

res = {}
for key, ele in zip(l, D1.items()):
    res[key] = dict([ele])
print(res)

a) {1: {‘sqatools’: 8}, 2: {‘python’: 6}}
b) {1: {‘sqatools’: 6}, 2: {‘python’: 8}}
c) {1: (‘sqatools’, 8), 2: (‘python’, 6)}
d) {1: (‘sqatools’, 6), 2: (‘python’, 8)}

Corresct answer is: a) {1: {‘sqatools’: 8}, 2: {‘python’: 6}}
Explanation: The code initializes an empty dictionary `res`. The `zip` function pairs the elements of the list `l` with the items (key-value pairs) of the dictionary `D1`. The loop iterates over these pairs. In each iteration, the line `res[key] = dict([ele])` creates a new dictionary using the `dict()` constructor with a single item `ele`, which is a key-value pair from `D1`. This newly created dictionary is assigned as the value to the key `key` in the `res` dictionary.

15). What is the output of the following code?

D1 = {1:’sqatools is best’,2:’for learning python’}
substr = [‘best’,’excellent’]
res = dict()

for key, val in D1.items():
    if not any(ele in val for ele in substr):
        res[key] = val
print(res)

a) {1: ‘sqatools is best’, 2: ‘for learning python’}
b) {2: ‘for learning python’}
c) {1: ‘sqatools is best’}
d) {}

Corresct answer is: b) {2: ‘for learning python’}
Explanation: The code is creating an empty dictionary res and iterating over the key-value pairs in D1 using D1.items(). Inside the loop, it checks if any element in substr is present in the value (val) of each key-value pair. If none of the elements in substr are found in the value, the key-value pair is added to the res dictionary.

16). Which two keys are printed when executing the following code?

D1 = {‘a’:18, ‘b’:50, ‘c’:36, ‘d’:47, ‘e’:60}
result = sorted(D1, key=D1.get, reverse=True)
print(result[:2])

a) ‘e’, ‘b’
b) ‘e’, ‘d’
c) ‘b’, ‘d’
d) ‘b’, ‘c’

Corresct answer is: a) ‘e’, ‘b’
Explanation: The code sorts the keys in the dictionary `D1` based on their corresponding values in descending order. The `key` parameter in the `sorted()` function specifies that the sorting should be based on the values obtained by calling `D1.get()` for each key. The `reverse=True` parameter ensures the sorting is in descending order. After sorting, the `result` variable will contain the keys in the following order: ‘e’, ‘b’, ‘d’, ‘c’, ‘a’. The `print(result[:2])` statement prints the first two elements of the `result` list, which are ‘e’ and ‘d’.

17). What is the output of the following code?

from collections import Counter
D1 = {‘a’: 10, ‘b’: 20, ‘c’: 25, ‘d’: 10, ‘e’: 30, ‘f’: 20}

result = Counter(D1.values())
print(result)

a) {10: 2, 20: 2, 25: 1, 30: 1}
b) {2: 10, 20: 1, 25: 1, 30: 1}
c) {1: 2, 2: 2, 10: 2, 20: 2, 25: 1, 30: 1}
d) {10: 1, 20: 1, 25: 1, 30: 1}

Corresct answer is: a) {10: 2, 20: 2, 25: 1, 30: 1}
Explanation: The Counter class from the collections module is used to count the occurrences of elements in an iterable. In this case, `D1.values()` returns an iterable of the dictionary values. The output is a dictionary where the keys represent the unique values from `D1.values()`, and the values represent the count of each unique value in the iterable. The dictionary `D1` has the following values: [10, 20, 25, 10, 30, 20]. The count of `10` is `2`, the count of `20` is `2`, the count of `25` is `1`, and the count of `30` is `1`. 

18). What is the output of the following code?

from itertools import product
D1 = {1:[‘Virat Kohli’], 2:[‘Rohit Sharma’], 3:[‘Hardik Pandya’]}

for sub in product(*D1.values()):
    result = [dict(zip(D1, sub))]
print(result)

a) [{‘Virat Kohli’, ‘Rohit Sharma’, ‘Hardik Pandya’}]
b) [{‘1’: ‘Virat Kohli’}, {‘2’: ‘Rohit Sharma’}, {‘3’: ‘Hardik Pandya’}]
c) [{‘1’: ‘Virat Kohli’, ‘2’: ‘Rohit Sharma’, ‘3’: ‘Hardik Pandya’}]
d) [{‘1’, ‘2’, ‘3’}, {‘Virat Kohli’, ‘Rohit Sharma’, ‘Hardik Pandya’}]

Corresct answer is: c) [{‘1’: ‘Virat Kohli’, ‘2’: ‘Rohit Sharma’, ‘3’: ‘Hardik Pandya’}]
Explanation: The code uses the `itertools.product` function to generate all possible combinations of the values from the dictionary `D1`. The `product(*D1.values())` part unpacks the values of `D1` as arguments to `product` function. Each combination is then converted into a dictionary using `dict(zip(D1, sub))`, where `sub` represents a combination of values.

19). What is the output of the following code?

l = [‘abc’, ‘defg’, ‘hijkl’]
D1 = {}

for val in l:
    D1[len(val)] = val

print(D1)

a) {‘abc’: 3, ‘defg’: 4, ‘hijkl’: 5}
b) {3: ‘abc’, 4: ‘defg’, 5: ‘hijkl’}
c) {0: ‘abc’, 1: ‘defg’, 2: ‘hijkl’}
d) {‘abc’: 0, ‘defg’: 1, ‘hijkl’: 2}

Corresct answer is: b) {3: ‘abc’, 4: ‘defg’, 5: ‘hijkl’}
Explanation: The code creates an empty dictionary D1 and iterates over the list l. For each value in l, it assigns the value as a key to D1 and the length of the value as the corresponding value. Therefore, the output is {3: ‘abc’, 4: ‘defg’, 5: ‘hijkl’}.

20). What is the output of the following code?

A = {‘name’: 1, ‘age’: 2}
B = {‘name’: 1, ‘age’: 2, ‘course’: 3, ‘institute’: 4}

count_a = len(A)
count_b = len(B)

if count_a > count_b:
    print(“1st dictionary has maximum pairs”, count_a)
else:
    print(“2nd dictionary has maximum pairs”, count_b)

a) “1st dictionary has maximum pairs”, 2
b) “1st dictionary has maximum pairs”, 4
c) “2nd dictionary has maximum pairs”, 4
d) “2nd dictionary has maximum pairs”, 2

Corresct answer is: c) “2nd dictionary has maximum pairs”, 2
Explanation: In this code, the length (number of key-value pairs) of dictionary A is calculated and stored in the variable `count_a`. Similarly, the length of dictionary B is calculated and stored in `count_b`. Since `count_a` is not greater than `count_b`, the condition `count_a > count_b` evaluates to `False`. 

21). What will be the output of the following code?

D1 = {‘xyz’: [20, 40], ‘abc’: [10, 30]}
D2 = {}

for k, v in D1.items():
    for ele in v:
        D2[ele] = [k]
print(D2)

a) {20: [‘xyz’], 40: [‘xyz’], 10: [‘abc’], 30: [‘abc’]}
b) {20: [‘abc’], 40: [‘abc’], 10: [‘xyz’], 30: [‘xyz’]}
c) {‘xyz’: [20, 40], ‘abc’: [10, 30]}
d) {‘abc’: [20, 40], ‘xyz’: [10, 30]}

Corresct answer is: a) {20: [‘xyz’], 40: [‘xyz’], 10: [‘abc’], 30: [‘abc’]}
Explanation: The code iterates over the key-value pairs in D1 using the items() method. For each key-value pair, it then iterates over the elements in the value list. In each iteration, it assigns the key as the value of D2 with the current element as the key. Since the elements in the value lists are 20, 40, 10, and 30, the corresponding keys in D2 will be 20, 40, 10, and 30. Since the values in D1 are lists, and a new list is assigned as the value in D2, each key in D2 will have a list as its value. The list contains the corresponding key from D1. 

22). What is the output of the following code?

D1 = {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘d’: 20}
l = list(D1.items())
print(l)

a) [(‘a’, 19), (‘b’, 20), (‘c’, 21), (‘d’, 20)]
b) [(‘a’, 19), (‘c’, 21), (‘b’, 20), (‘d’, 20)]
c) [(‘b’, 20), (‘a’, 19), (‘c’, 21), (‘d’, 20)]
d) [(‘c’, 21), (‘d’, 20), (‘b’, 20), (‘a’, 19)]

Corresct answer is: a) [(‘a’, 19), (‘b’, 20), (‘c’, 21), (‘d’, 20)]
Explanation: The code converts the dictionary `D1` into a list of tuples using the `items()` method. The `items()` method returns a view object that contains key-value pairs of the dictionary. The list is created from this view object using the `list()` function. The order of the items in the list corresponds to the order in which they were added to the dictionary. In this case, the order is preserved, resulting in `[(‘a’, 19), (‘b’, 20), (‘c’, 21), (‘d’, 20)]` as the output.

23). What is the output of the following code?

Name = [‘Virat’, ‘Rohit’]
Defaults = {‘sport’: ‘cricket’, ‘salary’: 100000}
D1 = {}

for name in Name:
    D1[name] = Defaults
print(D1)

a) {‘Virat’: {‘sport’: ‘cricket’, ‘salary’: 100000}, ‘Rohit’: {‘sport’: ‘cricket’, ‘salary’: 100000}}
b) {‘Virat’: ‘cricket’, ‘Rohit’: ‘cricket’}
c) {‘Virat’: ‘cricket’, ‘Rohit’: 100000}
d) {‘Virat’: ‘Virat’, ‘Rohit’: ‘Rohit’}

Corresct answer is: a) {‘Virat’: {‘sport’: ‘cricket’, ‘salary’: 100000}, ‘Rohit’: {‘sport’: ‘cricket’, ‘salary’: 100000}}
Explanation: The code initializes an empty dictionary D1. It then iterates over the elements in the Name list. For each element, it assigns the value of the Defaults dictionary to the corresponding key in D1. Therefore, the output is {‘Virat’: {‘sport’: ‘cricket’, ‘salary’: 100000}, ‘Rohit’: {‘sport’: ‘cricket’, ‘salary’: 100000}}, where both keys in D1 have the same dictionary value from Defaults.

24). What is the output of the following code?

D1 = {‘a’:19,’b’: 20,’c’:21,’d’:20}
D1[‘e’] = D1.pop(‘d’)
print(D1)

a) {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘d’: 20}
b) {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘e’: 20}
c) {‘a’: 19, ‘b’: 20, ‘c’: 21}
d) {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘e’: 21}

Corresct answer is: b) {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘e’: 20}
Explanation: The code snippet creates a dictionary `D1` with four key-value pairs: {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘d’: 20}. The statement `D1[‘e’] = D1.pop(‘d’)` removes the key-value pair with the key ‘d’ from the dictionary `D1` using the `pop()` method. The `pop()` method returns the value associated with the popped key, which is 20 in this case. Then, a new key-value pair is added to the dictionary with the key ‘e’ and the value returned from `D1.pop(‘d’)`, which is 20.

25). What is the output of the following code?

D1 = {‘a’: [6, 7, 2, 8, 1], ‘b’: [2, 3, 1, 6, 8, 10], ‘d’: [1, 8, 2, 6, 9]}
l = []

for v in D1.values():
    for num in v:
        if num not in l:
            l.append(num)
print(“Sum: “, sum(l))

a) Sum: 0
b) Sum: 3
c) Sum: 39
d) Sum: 49

Corresct answer is: c) Sum: 46
Explanation: The code iterates over the values of the dictionary `D1`. It then iterates over the numbers in each value and checks if the number is already present in the list `l`. If not, it appends the number to `l`. Finally, the sum of all the unique numbers in `l` is calculated using `sum(l)`. In this case, the unique numbers are `[6, 7, 2, 8, 1, 3, 10, 9]`, and their sum is 46. 

Python Dictionary MCQ : Set 3

Python Dictionary MCQ

1). What is the output of the following code?

dict1 = {‘course’:’python’,’institute’:’sqatools’ }
dict2 = {‘name’:’omkar’}

dict2.update(dict1)
print(dict2)

a) {‘name’: ‘omkar’}
b) {‘name’: ‘omkar’, ‘course’: ‘python’, ‘institute’: ‘sqatools’}
c) {‘course’: ‘python’, ‘institute’: ‘sqatools’}
d) {‘course’: ‘python’, ‘institute’: ‘sqatools’, ‘name’: ‘omkar’}

Corresct answer is: d) {‘course’: ‘python’, ‘institute’: ‘sqatools’, ‘name’: ‘omkar’}
Explanation: The `update()` method merges the key-value pairs from `dict1` into `dict2`. Since `dict2` is being updated with the key-value pairs from `dict1`, the resulting dictionary will have all the key-value pairs from both dictionaries. Therefore, the output will be `{‘course’: ‘python’, ‘institute’: ‘sqatools’, ‘name’: ‘omkar’}`.

2). What is the output of the following code?

dict1 = {}

for i in range(1, 6):
    dict1[i] = i ** 2

print(dict1)

a) {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
b) {1: 1, 4: 8, 9: 27, 16: 64, 25: 125}
c) {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
d) {1: 2, 4: 8, 9: 18, 16: 32, 25: 50}

Corresct answer is: a) {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Explanation: The code initializes an empty dictionary `dict1` and then uses a for loop to iterate through the numbers 1 to 5. For each number, it assigns the square of the number as the value to the corresponding key in the dictionary. Therefore, the final dictionary will be {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}.

3). What is the output of the following code?

dict1 = {‘a’: 2, ‘b’: 4, ‘c’: 5}
result = 1

for val in dict1.values():
    result *= val

print(result)

a) 8
b) 20
c) 40
d) 60

Corresct answer is: c) 40
Explanation: The code initializes `result` as 1 and then iterates over the values in `dict1`. It multiplies each value with `result` using the `*=` operator. Therefore, the result is the product of all the values: `2 * 4 * 5 = 40`.

4). What is the output of the following code?

dict1 = {‘a’: 2, ‘b’: 4, ‘c’: 5}

if ‘c’ in dict1:
    del dict1[‘c’]
print(dict1)

a) {‘a’: 2, ‘b’: 4}
b) {‘a’: 2, ‘b’: 4, ‘c’: 5}
c) {‘a’: 2, ‘b’: 4, ‘c’: None}
d) Error

Corresct answer is: a) {‘a’: 2, ‘b’: 4}
Explanation: The code checks if the key ‘c’ is present in the dictionary using the `in` keyword. Since ‘c’ exists as a key in dict1, the block of code inside the `if` statement is executed. The `del` statement removes the key-value pair with the key ‘c’ from the dictionary. Therefore, the resulting dictionary is {‘a’: 2, ‘b’: 4}.

5). What is the output of the following code?

list1 = [‘name’, ‘sport’, ‘rank’, ‘age’]
list2 = [‘Virat’, ‘cricket’, 1, 32]

new_dict = dict(zip(list1, list2))
print(new_dict)

a) {‘name’: ‘Virat’, ‘sport’: ‘cricket’, ‘rank’: 1, ‘age’: 32}
b) {‘Virat’: ‘name’, ‘cricket’: ‘sport’, 1: ‘rank’, 32: ‘age’}
c) {‘name’: ‘Virat’, ‘sport’: ‘cricket’}
d) Error

Corresct answer is: a) {‘name’: ‘Virat’, ‘sport’: ‘cricket’, ‘rank’: 1, ‘age’: 32}
Explanation: The code creates a new dictionary by combining the elements of `list1` as keys and `list2` as values using the `zip()` function. The resulting dictionary has the key-value pairs {‘name’: ‘Virat’, ‘sport’: ‘cricket’, ‘rank’: 1, ‘age’: 32}.

6). What is the output of the following code?

dict1 = {‘a’: 10, ‘b’: 44, ‘c’: 60, ‘d’: 25}
list1 = []

for val in dict1.values():
    list1.append(val)

list1.sort()
print(“Minimum value: “, list1[0])
print(“Maximum value: “, list1[-1])

a) Minimum value: 10, Maximum value: 60
b) Minimum value: 25, Maximum value: 60
c) Minimum value: 10, Maximum value: 44
d) Minimum value: 25, Maximum value: 44

Corresct answer is: a) Minimum value: 10, Maximum value: 60
Explanation: The code creates a list, `list1`, and appends all the values from `dict1` to it. The list is then sorted in ascending order using the `sort()` method. The first element of the sorted list (`list1[0]`) is the minimum value, which is 10. The last element of the sorted list (`list1[-1]`) is the maximum value, which is 60. Therefore, the output will be “Minimum value: 10, Maximum value: 60”.

7). What is the output of the code snippet?

from collections import defaultdict
list1 = [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
print(“The original list: “, list1)

dict1 = defaultdict(list)
for val in list1:
    dict1[val].append(val)
print(“Similar grouped dictionary: “, dict1)

a) The original list: [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Similar grouped dictionary: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5, 5]}
b) The original list: [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Similar grouped dictionary: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5]}
c) The original list: [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Similar grouped dictionary: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5]}
d) The original list: [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Similar grouped dictionary: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5]}

Corresct answer is: c) The original list: [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Similar grouped dictionary: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5]}
Explanation: The code uses the `defaultdict` class from the `collections` module. A `defaultdict` is a subclass of a dictionary that provides a default value for a nonexistent key. In this code, the default value is an empty list.The code then creates an empty `defaultdict` called `dict1`. It iterates over each value in `list1`. For each value, it appends the value itself to the corresponding key in the dictionary. This results in grouping similar values together.The resulting similar grouped dictionary is printed as: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5]}

8). What is the output of the following code?

string = ‘learning python at sqa-tools’
Dict = {‘at’: ‘is’, ‘sqa-tools’: ‘fun’}

for key, value in Dict.items():
    string = string.replace(key, value)
print(string)

a) ‘learning python is fun’
b) ‘learning python at sqa-tools’
c) ‘learning python at fun’
d) ‘learning python is sqa-tools’

Corresct answer is: a) ‘learning python is fun’
Explanation: The code iterates over the key-value pairs in the dictionary `Dict`. For each key-value pair, it replaces all occurrences of the key in the `string` with the corresponding value using the `replace()` method. In the first iteration, ‘at’ is replaced with ‘is’, resulting in the string: ‘learning python is sqa-tools’. In the second iteration, ‘sqa-tools’ is replaced with ‘fun’, resulting in the final string: ‘learning python is fun’. The modified `string` is printed, which outputs ‘learning python is fun’.

9). What is the output of the following code?

String = ‘sqatools is best for learning python’
Dict = {‘best’:2,’learning’:6}

str2 = “”
for word in String.split(” “):
    if word not in Dict:
        str2 += word + ” “
print(str2)

a) ‘sqatools is best for learning python’
b) ‘sqatools is for python’
c) ‘is for python’
d) ‘sqatools is best for’

Corresct answer is: b) ‘sqatools is for python’
Explanation: The code iterates over each word in the `String` variable, splitting it by spaces. It checks if each word is present in the `Dict` dictionary. If a word is not found in the dictionary, it is appended to the `str2` variable followed by a space. In this case, the words ‘best’ and ‘learning’ are present in the dictionary, so they are not included in `str2`. Hence, the output is ‘sqatools is for python’.

10). What is the output of the following code?

dict1 = {}

if len(dict1) > 0:
    print(“Dictionary is not empty”)
else:
    print(“Dictionary is empty”

a) “Dictionary is not empty”
b) “Dictionary is empty”
c) Error
d) None

Corresct answer is: b) “Dictionary is empty”
Explanation: The code initializes an empty dictionary `dict1`. The `len(dict1)` function returns the number of key-value pairs in the dictionary, which is 0 in this case. Since the condition `len(dict1) > 0` is not satisfied, the code enters the `else` block and prints “Dictionary is empty”.

11). What will be the output of the following code snippet?

Dict1 = {‘x’:10,’y’:20,’c’:50,’f’:44 }
Dict2 = {‘x’:60,’c’:25,’y’:56}

for key in Dict1:
    for k in Dict2:
        if key == k:
            a = Dict1[key]+Dict2[k]
            Dict2[key] = a
print(Dict2)

a) {‘x’: 70, ‘c’: 75, ‘y’: 76}
b) {‘x’: 60, ‘c’: 25, ‘y’: 56}
c) {‘x’: 10, ‘y’: 20, ‘c’: 50, ‘f’: 44}
d) {‘x’: 10, ‘y’: 20, ‘c’: 50, ‘f’: 44, ‘y’: 76}

Corresct answer is: a) {‘x’: 70, ‘c’: 75, ‘y’: 76}
Explanation: The code iterates through each key in Dict1 and checks if it exists as a key in Dict2. If a matching key is found, the corresponding values from Dict1 and Dict2 are added together and stored in variable ‘a’. Then, the key-value pair in Dict2 is updated with the new value ‘a’. Finally, the updated Dict2 is printed, which will be {‘x’: 70, ‘c’: 75, ‘y’: 76}. The value for key ‘x’ is 10 + 60 = 70, the value for key ‘c’ is 50 + 25 = 75, and the value for key ‘y’ is 20 + 56 = 76. The key ‘f’ from Dict1 is not present in Dict2, so it remains unchanged in the final result.

12). What is the output of the following Python code?


list1 = [{‘name1′:’robert’},{‘name2′:’john’},{‘name3′:’jim’}, {‘name4′:’robert’}]
list2 = []
for val in list1:
    for ele in val.values():
        if ele not in list2:
            list2.append(ele)
print(list2)

a) [‘robert’, ‘john’, ‘jim’]
b) [‘robert’, ‘john’, ‘jim’, ‘robert’]
c) [‘john’, ‘jim’]
d) [‘robert’]

Corresct answer is: a) [‘robert’, ‘john’, ‘jim’]
Explanation: The code iterates over each dictionary in `list1` using the variable `val`. Then, within each dictionary, it retrieves the value using the `values()` method. The retrieved value is checked if it already exists in `list2`. If not, it is appended to `list2`. Since the value ‘robert’ appears twice in `list1`, it is added twice to `list2`. Therefore, the output will be `[‘robert’, ‘john’, ‘jim’]`.

13). What is the output of the following code?

import pandas as pd
dict1 = {‘names’:[‘virat’,’messi’,’kobe’],’sport’:[‘cricket’,’football’,’basketball’]}

table = pd.DataFrame(dict1)
print(table)

a)

| | names | sport |
|—|——-|————|
| 0 | virat | cricket |
| 1 | messi | football |
| 2 | kobe | basketball |

b)

| | names | sport |
|—|——-|————|
| 0 | virat | football |
| 1 | messi | cricket |
| 2 | kobe | basketball |

c)

| | names | sport |
|—|——-|————|
| 0 | virat | basketball |
| 1 | messi | cricket |
| 2 | kobe | football |

d)

| | names | sport |
|—|——-|————|
| 0 | virat | cricket |
| 1 | kobe | basketball |
| 2 | messi | football |

Corresct answer is: a)

| | names | sport |
|—|——-|————|
| 0 | virat | cricket |
| 1 | messi | football |
| 2 | kobe | basketball |

Explanation: The code creates a dictionary called `dict1` with two keys: ‘names’ and ‘sport’, and their corresponding values as lists. It then creates a DataFrame using `pd.DataFrame()` by passing the dictionary as an argument. The DataFrame is displayed using `print(table)`. The resulting table has three rows, where each row represents a player’s name and their associated sport.

14). What is the output of the following code?

list1 = [2, 5, 8, 1, 2, 6, 8, 5, 2]
dict1 = {}

for val in list1:
    dict1[val] = list1.count(val)
print(dict1)

a) {1: 1, 2: 3, 5: 2, 6: 1, 8: 2}
b) {2: 3, 5: 2, 8: 2, 1: 1, 6: 1}
c) {2: 3, 5: 2, 8: 2, 1: 1, 6: 1, 0: 0}
d) {2: 3, 5: 2, 8: 2, 1: 1, 6: 1, 9: 0}

Corresct answer is: a) {1: 1, 2: 3, 5: 2, 6: 1, 8: 2}
Explanation: The code creates an empty dictionary `dict1` and then iterates over each value in `list1`. For each value, it counts the number of occurrences using `list1.count(val)` and assigns that count as the value in the dictionary with the value itself as the key. The resulting dictionary will contain the counts of each unique value from the list.In this case, the output dictionary will be `{1: 1, 2: 3, 5: 2, 6: 1, 8: 2}`. Value 1 appears once, value 2 appears three times, value 5 appears twice, value 6 appears once, and value 8 appears twice.

15). What is the output of the following code?

dict1 = {‘m1’: 25, ‘m2’: 20, ‘m3’: 15}
total = 0
count = 0

for val in dict1.values():
    total += val
    count += 1
print(“Mean: “, (total / count))

a) Mean: 25
b) Mean: 20
c) Mean: 15
d) Mean: 20.0

Corresct answer is: d) Mean: 20.0
Explanation: The code calculates the mean of the values in the dict1 dictionary. It iterates over the values using a loop, calculates the total sum of the values, and increments the count. Finally, it prints the mean by dividing the total by the count. In this case, the mean is 20.0.

16). What is the output of the following code?

list1 = [‘a’, ‘b’, ‘c’, ‘d’]
new_dict = current = {}

for char in list1:
    current[char] = {}
    current = current[char]
print(new_dict)

a) {‘a’: {‘b’: {‘c’: {‘d’: {}}}}}
b) {‘d’: {‘c’: {‘b’: {‘a’: {}}}}}
c) {‘a’: {}, ‘b’: {}, ‘c’: {}, ‘d’: {}}
d) {‘d’: {}, ‘c’: {}, ‘b’: {}, ‘a’: {}}

Corresct answer is: a) {‘a’: {‘b’: {‘c’: {‘d’: {}}}}}
Explanation: The given code iterates over each character in the list list1. It creates nested dictionaries where each character becomes a key for the next nested dictionary.

17). What is the output of the following code?

dict1 = {‘a1’: [1, 5, 3], ‘a2’: [10, 6, 20]}
for val in dict1.values():
    val.sort()
print(dict1)

a) {‘a1’: [1, 3, 5], ‘a2’: [6, 10, 20]}
b) {‘a1’: [1, 5, 3], ‘a2’: [10, 6, 20]}
c) {‘a1’: [1, 5, 3], ‘a2’: [6, 10, 20]}
d) {‘a1’: [1, 3, 5], ‘a2’: [10, 20, 6]}

Corresct answer is: a) {‘a1’: [1, 3, 5], ‘a2’: [6, 10, 20]}
Explanation: The code iterates over the values in `dict1` using a for loop. Each value, which is a list, is sorted in ascending order using the `sort()` method. After the loop, the dictionary `dict1` is printed. Since lists are mutable objects, sorting the values in-place affects the original dictionary. Therefore, the output will be `{‘a1’: [1, 3, 5], ‘a2’: [6, 10, 20]}` with the values sorted in ascending order within each list.

18). What is the output of the following code?

dict1 = {‘virat’:{‘sport’:’cricket’,’team’:’india’},
‘messi’:{‘sport’:’football’,’team’:’argentina’}}
for key, val in dict1.items():
    print(key)
    for k,v in val.items():
        print(k,”:”,v)

a) virat
sport: cricket
team: india
messi
sport: football
team: argentina
b) virat
sport: cricket
messi
sport: football
team: argentina
c) virat: sport: cricket, team: india
messi: sport: football, team: argentina
d) sport: cricket, team: india
sport: football, team: argentina

Corresct answer is: a) virat
sport: cricket
team: india
messi
sport: football
team: argentina
Explanation: The code iterates over the items of the `dict1` dictionary. For each key-value pair, it prints the key and then iterates over the nested dictionary `val`. For each key-value pair in `val`, it prints the key and value. Therefore, the output includes the keys ‘virat’ and ‘messi’, followed by their respective key-value pairs from the nested dictionaries.

19). What is the output of the following code?

dict1 = {‘sqa’:[1,4,6],’tools’:[3,6,9]}
list1 = []

for key,val in dict1.items():
    l = []
    l.append(key)
    for ele in val:
        l.append(ele)
    list1.append(list(l))
print(list1)

a) [[‘sqa’, 1, 4, 6], [‘tools’, 3, 6, 9]]
b) [[‘sqa’, [1, 4, 6]], [‘tools’, [3, 6, 9]]]
c) [[‘sqa’, 1], [‘sqa’, 4], [‘sqa’, 6], [‘tools’, 3], [‘tools’, 6], [‘tools’, 9]]
d) [[‘sqa’, [1, 4, 6]], [‘tools’, [3, 6, 9]], [‘sqa’, [1, 4, 6]], [‘tools’, [3, 6, 9]]]

Corresct answer is: a) [[‘sqa’, 1, 4, 6], [‘tools’, 3, 6, 9]]
Explanation: The code iterates over the key-value pairs in the dictionary. For each pair, it creates a new list and appends the key followed by the values from the corresponding list. These lists are then appended to the list1. The final output is [[‘sqa’, 1, 4, 6], [‘tools’, 3, 6, 9]].

20). What is the output of the following code?

dict1 = [{‘sqa’: 123, ‘tools’: 456}]
l = []
for ele in dict1:
    for k in ele.keys():
        a = []
        a.append(k)
        l.append(a)
    for v in ele.values():
        b = []
        b.append(v)
        l.append(b)
print(l)

a) [[‘sqa’], [123], [‘tools’], [456]]
b) [{‘sqa’}, {123}, {‘tools’}, {456}]
c) [[‘sqa’, ‘tools’], [123, 456]]
d) [[{‘sqa’: 123, ‘tools’: 456}]]

Corresct answer is: a) [[‘sqa’], [123], [‘tools’], [456]]
Explanation: The code iterates over the list `dict1` which contains a single dictionary element. For each dictionary element, it retrieves the keys using `ele.keys()` and appends them as separate lists to `l`. Then it retrieves the values using `ele.values()` and appends them as separate lists to `l`. Finally, it prints the resulting list `l`, which contains individual lists for each key and value. Therefore, the output will be `[[‘sqa’], [123], [‘tools’], [456]]`.

21). What is the output of the following code?

dict1 = {‘virat’: [‘match1’, ‘match2’, ‘match3’], ‘rohit’: [‘match1’, ‘match2’]}
count = 0

for val in dict1.values():
    for ele in val:
        count += 1
print(“Items in the list of values: “, count)

a) 3
b) 5
c) 6
d) 8

Corresct answer is: b) 5
Explanation: The code snippet iterates over the values of the dictionary `dict1`. For each value, it iterates over the elements using a nested loop. In this case, the values are `[‘match1’, ‘match2’, ‘match3’]` and `[‘match1’, ‘match2’]`. So, the total count of items in the list of values is 5.

22). What is the output of the following code?

dict1 = {‘Math’:70,’Physics’:90,’Chemistry’:67}
a = sorted(dict1.items(), key = lambda val:val[1], reverse = True)
print(a)

a) [(‘Physics’, 90), (‘Math’, 70), (‘Chemistry’, 67)]
b) [(‘Math’, 70), (‘Physics’, 90), (‘Chemistry’, 67)]
c) [(‘Chemistry’, 67), (‘Math’, 70), (‘Physics’, 90)]
d) [(‘Physics’, 90), (‘Chemistry’, 67), (‘Math’, 70)]

Corresct answer is: a) [(‘Physics’, 90), (‘Math’, 70), (‘Chemistry’, 67)]
Explanation: The code sorts the dictionary items based on the values in descending order. The sorted() function is called with the key argument set to a lambda function that returns the value of each item. The reverse parameter is set to True to sort in descending order. The output is a list of tuples, where each tuple contains a key-value pair from the original dictionary, sorted by the values in descending order.

23). What is the output of the following code?

dict1 = [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1’: 80, ‘p2’: 70}]
for d in dict1:
n1 = d.pop(‘p1’)
n2 = d.pop(‘p2’)
d[‘p1+p2’] = (n1 + n2) / 2

print(dict1)

a) [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1+p2’: 150}]
b) [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1+p2’: 75}]
c) [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1’: 80, ‘p2’: 70, ‘p1+p2’: 75}]
d) Error

Corresct answer is: b) [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1+p2’: 75}]
Explanation: The code iterates over the list of dictionaries. For each dictionary, it removes the ‘p1’ and ‘p2’ keys and calculates their average. Then, it adds a new key ‘p1+p2’ with the calculated average value. Finally, it prints the modified list of dictionaries. In this case, the output will be [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1+p2’: 75}] because the average of 80 and 70 is 75.

24). What is the output of the given code?

dict1 = {‘k1′:’p’,’k2′:’q’,’k3′:’r’}
dict2 = {‘k1′:’p’,’k2′:’s’}

for key in dict1:
    if key in dict2:
        print(f”{key} is present in both dictionaries”)
    else:
        print(f”{key} is present not in both dictionaries”)

a) k1 is present in both dictionaries
k2 is present not in both dictionaries
k3 is present not in both dictionaries
b) k1 is present in both dictionaries
k2 is present in both dictionaries
k3 is present not in both dictionaries
c) k1 is present in both dictionaries
k2 is present in both dictionaries
k3 is present in both dictionaries
d) k1 is present in both dictionaries
k2 is present not in both dictionaries
k3 is present in both dictionaries

Corresct answer is: b) k1 is present in both dictionaries
k2 is present in both dictionaries
k3 is present not in both dictionaries
Explanation: The given code iterates over the keys of `dict1`. It checks if each key is present in `dict2`. If a key is found in both dictionaries, it prints that the key is present in both dictionaries. If a key is only present in `dict1`, it prints that the key is not present in both dictionaries. In this case, ‘k1’ is present in both dictionaries, ‘k2’ is present in both dictionaries, and ‘k3’ is present only in `dict1`.

25). What is the output of the code snippet?

l1 = []
for i in range(1, 6):
    l1.append(i)

l2 = []
for i in range(6, 11):
    l2.append(i)

l3 = []
for i in range(11, 16):
    l3.append(i)

dict1 = {}
dict1[“a”] = l1
dict1[“b”] = l2
dict1[“c”] = l3
print(dict1)

a) {‘a’: [1, 2, 3, 4, 5], ‘b’: [6, 7, 8, 9, 10], ‘c’: [11, 12, 13, 14, 15]}
b) {‘a’: [1, 2, 3, 4, 5], ‘b’: [1, 2, 3, 4, 5], ‘c’: [1, 2, 3, 4, 5]}
c) {‘a’: [1, 2, 3, 4], ‘b’: [6, 7, 8, 9], ‘c’: [11, 12, 13, 14]}
d) {‘a’: [1, 2, 3, 4], ‘b’: [5, 6, 7, 8], ‘c’: [9, 10, 11, 12]}

Corresct answer is: a) {‘a’: [1, 2, 3, 4, 5], ‘b’: [6, 7, 8, 9, 10], ‘c’: [11, 12, 13, 14, 15]}
Explanation: The code creates three lists, `l1`, `l2`, and `l3`, and populates them with consecutive numbers using range(). Then, a dictionary `dict1` is created with keys ‘a’, ‘b’, and ‘c’, and their respective values are assigned as `l1`, `l2`, and `l3`. Finally, the dictionary is printed, resulting in `{‘a’: [1, 2, 3, 4, 5], ‘b’: [6, 7, 8, 9, 10], ‘c’: [11, 12, 13, 14, 15]}`.

Python Dictionary MCQ : Set 2

Python Dictionary MCQ

1). Which method returns a string representation of a dictionary?

a) str()
b) repr()
c) string()
d) __str__()

Corresct answer is: d) __str__()
Explanation: The __str__() method returns a string representation of a dictionary. It can be customized by overriding the method in a custom dictionary class.

2). Which method returns a dictionary’s iterator for keys?

a) keys()
b) iterate_keys()
c) key_iterator()
d) __iter__()

Corresct answer is: a) keys()
Explanation: The keys() method returns an iterator for the keys in a dictionary, allowing iteration over the keys.

3). Which method returns a dictionary’s iterator for values?

a) values()
b) value_iterator()
c) iterate_values()
d) __iter__()

Corresct answer is: a) values()
Explanation: The values() method returns an iterator for the values in a dictionary, allowing iteration over the values.

4). Which method returns a dictionary’s iterator for key-value pairs as tuples?

a) iteritems()
b) items()
c) iterate_pairs()
d) __iter__()

Corresct answer is: b) items()
Explanation: The items() method returns an iterator for the key-value pairs in a dictionary as tuples, allowing iteration over the key-value pairs.


5). Which method returns the sum of all the values in a dictionary?

a) sum()
b) total()
c) add_values()
d) __sum__()

Corresct answer is: a) sum()
Explanation: The sum() method can be used to calculate the sum of all the values in a dictionary.

6). In Python which method returns a new dictionary with only the specified keys and their values?

a) subset()
b) filter()
c) select()
d) __getitem__()

Corresct answer is: b) filter()
Explanation: The filter() method returns a new dictionary with only the specified keys and their corresponding values.

7). Which method returns a new dictionary with the specified default value for keys that are not present in the original dictionary?

a) set_default()
b) default()
c) default_value()
d) __missing__()

Corresct answer is: a) set_default()
Explanation: The set_default() method returns a new dictionary with the specified default value for keys that are not present in the original dictionary.

8). Which method returns the number of key-value pairs in a dictionary?

a) count()
b) size()
c) length()
d) __len__()

Corresct answer is: d) __len__()
Explanation: The __len__() method returns the number of key-value pairs in a dictionary.

9). Which method returns a copy of a dictionary?

a) clone()
b) copy()
c) duplicate()
d) __copy__()

Corresct answer is: b) copy()
Explanation: The copy() method returns a shallow copy of a dictionary.

10). Which method can be used to clear all the key-value pairs in a dictionary?

a) clear()
b) empty()
c) remove_all()
d) __clear__()

Corresct answer is: a) clear()
Explanation: The clear() method removes all the key-value pairs from a dictionary, making it empty.

11). Which method can be used to check if a specific value is present in a dictionary?

a) contains()
b) has_value()
c) in_value()
d) __contains__()

Corresct answer is: d) __contains__()
Explanation: The __contains__() method can be used to check if a specific value is present in a dictionary.

12). Which method can be used to combine two dictionaries into one?

a) combine()
b) merge()
c) join()
d) __add__()

Corresct answer is: b) merge()
Explanation: The merge() method can be used to combine two dictionaries into one.

13). Which method can be used to remove a specific key-value pair from a dictionary?

a) remove()
b) delete()
c) pop()
d) __remove__()

Corresct answer is: c) pop()
Explanation: The pop() method can be used to remove a specific key-value pair from a dictionary based on the given key.

14). What is the output of the following code?

dictionary = {‘a’: 5, ‘b’:3, ‘c’: 6, ‘d’: 8}
for val in dictionary:
print(val,”:”, dictionary[val]**2)

a) a: 5, b: 3, c: 6, d: 8
b) a: 25, b: 9, c: 36, d: 64
c) a: 5^2, b: 3^2, c: 6^2, d: 8^2
d) a: 25, b: 3, c: 36, d: 8

Corresct answer is: b) a: 25, b: 9, c: 36, d: 64
Explanation: The code iterates over the dictionary using a for loop. In each iteration, it prints the key followed by a colon and the square of the corresponding value. The output will be “a: 25, b: 9, c: 36, d: 64” because the values are squared before printing.

15). What will be the output of the following code?

D1 = {‘name’:’john’,’city’:’Landon’,’country’:’UK’}
D2 = {}

for val in D1:
D2[val] = D1[val]
print(D2)

a) {‘name’:’john’,’city’:’Landon’,’country’:’UK’}
b) {‘john’:’name’,’Landon’:’city’,’UK’:’country’}
c) {‘name’,’john’,’city’,’Landon’,’country’,’UK’}
d) {‘john’,’Landon’,’UK’}

Corresct answer is: a) {‘name’:’john’,’city’:’Landon’,’country’:’UK’}
Explanation: The code iterates over the key-value pairs in dictionary D1. It then assigns each key-value pair to the corresponding key in dictionary D2. Therefore, D2 will have the same key-value pairs as D1, resulting in the output {‘name’:’john’,’city’:’Landon’,’country’:’UK’}.

16). What is the output of the following code?

dict1 = {‘Name’:’Harry’,’Rollno’:345,’Address’:’Jordan’}
dict2 = {‘Age’:25,’salary’: ‘$25k’}
dict1.update(dict2)
print(dict1)

a){‘Name’:’Harry’,’Rollno’:345,’Address’:’Jordan’,’Age’:25,’salary’: ‘$25k’}
b) {‘Name’:’Harry’,’Age’:25,’Rollno’:345,’salary’: ‘$25k’,’Address’:’Jordan’}
c) {‘Name’:’Harry’,’Rollno’:345,’Address’:’Jordan’}
d) {‘Age’:25,’salary’: ‘$25k’}

Corresct answer is: a) {‘Name’:’Harry’,’Rollno’:345,’Address’:’Jordan’,’Age’:25,’salary’: ‘$25k’}
Explanation: The update() method is used to add the key-value pairs from dict2 into dict1. The original values in dict1 are updated with the corresponding values from dict2. Therefore, the output will be {‘Name’:’Harry’,’Rollno’:345,’Address’:’Jordan’,’Age’:25,’salary’: ‘$25k’}

17). What is the output of the following code?

dict1 = {1:25, 5:’abc’, 8:’pqr’, 21:’xyz’, 12:’def’, 2:’utv’}

list1 = [[val, dict1[val]] for val in dict1 if val%2 == 0]
list2 = [[val, dict1[val]] for val in dict1 if val%2 != 0]

print(“Even key = “, list1)
print(“Odd key = “, list2)

a) Even key = [[8, ‘pqr’], [12, ‘def’], [2, ‘utv’]]
Odd key = [[1, 25], [5, ‘abc’], [21, ‘xyz’]]
b) Even key = [[1, 25], [5, ‘abc’], [21, ‘xyz’]]
Odd key = [[8, ‘pqr’], [12, ‘def’], [2, ‘utv’]]
c) Even key = []
Odd key = [[1, 25], [5, ‘abc’], [21, ‘xyz’], [8, ‘pqr’], [12, ‘def’], [2, ‘utv’]]
d) Even key = [[1, 25], [5, ‘abc’], [21, ‘xyz’], [8, ‘pqr’], [12, ‘def’], [2, ‘utv’]]
Odd key = []

Corresct answer is: a) Even key = [[8, ‘pqr’], [12, ‘def’], [2, ‘utv’]]
Odd key = [[1, 25], [5, ‘abc’], [21, ‘xyz’]]
Explanation: In the given code, `list1` is generated using a list comprehension that iterates over the values in `dict1`. It only includes key-value pairs where the key is even. Similarly, `list2` is generated using a list comprehension that includes key-value pairs where the key is odd. The code then prints the contents of `list1` and `list2`. The output shows that `list1` contains the even key-value pairs and `list2` contains the odd key-value pairs from `dict1`.

18). What will be the output of the following code?

list1 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
list2 = [12, 23, 24, 25, 15, 16]
dict1 = {}

for a, b in zip(list1, list2):
    dict1[a] = b

print(dict1)

a) {‘a’: 12, ‘b’: 23, ‘c’: 24, ‘d’: 25, ‘e’: 15}
b) {‘a’: 12, ‘b’: 23, ‘c’: 24, ‘d’: 25, ‘e’: 15, ’16’: None}
c) {‘a’: 12, ‘b’: 23, ‘c’: 24, ‘d’: 25, ‘e’: 15, ’16’: 16}
d) Error

Corresct answer is: a) {‘a’: 12, ‘b’: 23, ‘c’: 24, ‘d’: 25, ‘e’: 15}
Explanation: The code uses the `zip()` function to iterate over `list1` and `list2` simultaneously. It then assigns each element of `list1` as a key and each element of `list2` as a value in `dict1`. The resulting dictionary will be `{‘a’: 12, ‘b’: 23, ‘c’: 24, ‘d’: 25, ‘e’: 15}`.

19). What is the output of the following code?

list1 = [4, 5, 6, 2, 1, 7, 11]
dict1 = {}

for val in list1:
    if val % 2 == 0:
        dict1[val] = val**2
    else:
        dict1[val] = val**3
print(dict1)

a) {4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}
b) {4: 8, 5: 9, 6: 10, 2: 4, 1: 1, 7: 49, 11: 121}
c) {4: 8, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 121}
d) {4: 16, 5: 9, 6: 10, 2: 4, 1: 1, 7: 343, 11: 1331}

Corresct answer is: a) {4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}
Explanation: The code initializes an empty dictionary `dict1` and iterates over the elements of `list1`. For each element, if it is even (divisible by 2), the element is used as a key in `dict1` with its square value as the corresponding value. If it is odd, the element is used as a key with its cube value as the corresponding value. The final dictionary `dict1` will contain the following key-value pairs: `{4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}`.

20). What is the output of the following code?

dict1 = {‘Name’: ‘Harry’, ‘Rollno’: 345, ‘Address’: ‘Jordan’}
dict1.clear()
print(dict1)

a) {}
b) {‘Name’: ‘Harry’, ‘Rollno’: 345, ‘Address’: ‘Jordan’}
c) Error
d) None

Corresct answer is: a) {}
Explanation: The `clear()` method removes all the key-value pairs from the dictionary, making it empty. Therefore, the output is an empty dictionary `{}`.

21). What is the output of the following code?

string = “SQAToolss”
dict1 = {}

for char in string:
    dict1[char] = string.count(char)

print(dict1)

a) {‘S’: 2, ‘Q’: 1, ‘A’: 1, ‘T’: 1, ‘o’: 2, ‘l’: 1, ‘s’: 2}
b) {‘S’: 1, ‘Q’: 1, ‘A’: 1, ‘T’: 1, ‘o’: 2, ‘l’: 1, ‘s’: 2}
c) {‘S’: 1, ‘Q’: 1, ‘A’: 1, ‘T’: 1, ‘o’: 1, ‘l’: 1, ‘s’: 2}
d) {‘S’: 1, ‘Q’: 1, ‘A’: 1, ‘T’: 1, ‘o’: 1, ‘l’: 1, ‘s’: 1}

Corresct answer is: a) {‘S’: 2, ‘Q’: 1, ‘A’: 1, ‘T’: 1, ‘o’: 2, ‘l’: 1, ‘s’: 2}
Explanation: The code initializes an empty dictionary `dict1` and iterates over each character in the string “SQAToolss”. For each character, it counts the number of occurrences in the string using the `count()` method and assigns the count as the value for that character in the dictionary. The final dictionary will contain the counts of each character in the string.

22). What is the output of the following code?

dict1 = {‘d’:14,’b’:52,’a’:13,’c’: 1}
sorted_ = {key: value for key, value in sorted(dict1.items(), key=lambda item: item[1])}
print(sorted_)

a) {‘c’: 1, ‘a’: 13, ‘d’: 14, ‘b’: 52}
b) {‘a’: 13, ‘b’: 52, ‘c’: 1, ‘d’: 14}
c) {‘b’: 52, ‘d’: 14, ‘a’: 13, ‘c’: 1}
d) {‘c’: 1, ‘b’: 52, ‘a’: 13, ‘d’: 14}

Corresct answer is: a) {‘c’: 1, ‘a’: 13, ‘d’: 14, ‘b’: 52}
Explanation: The code snippet sorts the dictionary `dict1` based on the values in ascending order using a lambda function as the sorting key. The resulting dictionary `sorted_` will have key-value pairs sorted by their values from smallest to largest.The output will be `{‘c’: 1, ‘a’: 13, ‘d’: 14, ‘b’: 52}`.

23). What is the output of the following code?

D1 = {‘x’: 23, ‘y’: 10, ‘z’: 7}
total = 0
for val in D1.values():
    total += val
print(total)

a) 23
b) 40
c) 50
d) 7

Corresct answer is: b) 40
Explanation: The code calculates the sum of all the values in the dictionary D1. The values are accessed using the values() method and then added to the total variable using a loop. The sum of 23 + 10 + 7 is 40, which is printed as the output.

24). What is the output of the following code?

D1 = {‘city’:’pune’,’state’:’maharashtra’}
count = 0

for key in D1.keys():
    if key == “Country”:
        count += 1

if count > 0:
print(“Key exists”)
else:
print(“Key does not exist”)

a) Key exists
b) Key does not exist
c) Error
d) None

Corresct answer is: b) Key does not exist
Explanation: In the given code, the loop iterates over the keys of the dictionary `D1`. It checks if any key is equal to “Country”. Since there is no key with the name “Country” in the dictionary, the `count` variable remains 0. After the loop, the code checks if `count` is greater than 0. Since it is not, the output will be “Key does not exist”.

25). What is the output of the following code?

n = 4
D1 = {}

for i in range(1, n+1):
    D1.update({i: i**3})
print(D1)

a) {1: 1, 2: 4, 3: 9, 4: 16}
b) {1: 1, 2: 8, 3: 27, 4: 64}
c) {1: 1, 2: 9, 3: 27, 4: 81}
d) {1: 1, 2: 16, 3: 81, 4: 256}

Corresct answer is: b) {1: 1, 2: 8, 3: 27, 4: 64}
Explanation: The code initializes an empty dictionary, `D1`. It then iterates over the numbers from 1 to 4 (inclusive) using the `range()` function. For each number, it updates the dictionary `D1` with a key-value pair, where the key is the number itself, and the value is the cube of the number. After the loop, the resulting dictionary `D1` will contain the key-value pairs `{1: 1, 2: 8, 3: 27, 4: 64}`.

Python Dictionary MCQ : Set 1

Python Dictionary MCQ

1). What is a dictionary in Python?

a) An ordered collection of elements
b) A sequence of key-value pairs
c) A data structure for storing integers
d) A built-in function in Python

Corresct answer is: b) A sequence of key-value pairs
Explanation: A dictionary in Python is an unordered collection of key-value pairs, where each key is unique.

2). Which symbol is used to define a dictionary in Python?

a) []
b) ()
c) {}
d) //

Corresct answer is: c) {}
Explanation: Curly braces ({}) are used to define a dictionary in Python.

3). What is the output of the following code?

my_dict = {‘name’: ‘Ketan’, ‘age’: 29}
print(my_dict[‘name’])

a) ‘name’
b) ‘John’
c) {‘name’: ‘John’}
d) 25

Corresct answer is: b) ‘Ketan’
Explanation: The code accesses the value associated with the key ‘name’ in the dictionary and prints it, which is ‘John’.

4). Can a dictionary contain duplicate keys?

a) Yes
b) No

Corresct answer is: b) No
Explanation: Dictionary keys must be unique. If a duplicate key is encountered during assignment, the last value assigned to that key will be retained.

5). How do you add a new key-value pair to a dictionary?

a) Using the append() method
b) Using the add() method
c) Using the insert() method
d) By assigning a value to a new key

Corresct answer is: d) By assigning a value to a new key
Explanation: To add a new key-value pair to a dictionary, you can simply assign a value to a new key using the assignment operator (=).

6). What happens when you access a key that does not exist in a dictionary?

a) An error is raised
b) None is returned
c) An empty string is returned
d) The dictionary expands to include the new key

Corresct answer is: a) An error is raised
Explanation: Accessing a key that does not exist in a dictionary raises a KeyError.

7). Which of the following methods in Python is used to remove a key-value pair from a dictionary?

a) delete()
b) remove()
c) discard()
d) del

Corresct answer is: d) del
Explanation: The `del` keyword is used to remove a key-value pair from a dictionary by specifying the key to be deleted.

8). What is the purpose of the keys() method in a dictionary?

a) To retrieve all the keys in a dictionary
b) To retrieve all the values in a dictionary
c) To retrieve both the keys and values in a dictionary
d) To sort the dictionary keys in ascending order

Corresct answer is: a) To retrieve all the keys in a dictionary
Explanation: The keys() method returns a view object that contains all the keys in the dictionary.

9). Which method returns a list of all the values in a dictionary?

a) values()
b) items()
c) get()
d) keys()

Corresct answer is: a) values()
Explanation: The values() method returns a view object that contains all the values in the dictionary.

10). Which method can be used to iterate over both the keys and values in a dictionary?

a) items()
b) keys()
c) values()
d) iterate()

Corresct answer is: a) items()
Explanation: The items() method returns a view object that contains key-value pairs as tuples, allowing iteration over both keys and values.

11). Which method returns the value associated with a specified key in a dictionary?

a) get()
b) value()
c) fetch()
d) retrieve()

Corresct answer is: a) get()
Explanation: The get() method returns the value associated with a specified key in a dictionary. If the key does not exist, it can return a default value.

12). Which method can be used to check if a key exists in a dictionary?

a) has_key()
b) contains()
c) in
d) exists()

Corresct answer is: c) in
Explanation: The `in` operator can be used to check if a key exists in a dictionary. It returns a Boolean value (True or False).

13). Which method is used to clear all the key-value pairs from a dictionary?

a) clear()
b) delete()
c) remove()
d) empty()

Corresct answer is: a) clear()
Explanation: The clear() method removes all the key-value pairs from a dictionary, making it an empty dictionary.

14). Which method is used to update a dictionary with the key-value pairs from another dictionary?

a) merge()
b) update()
c) add()
d) append()

Corresct answer is: b) update()
Explanation: The update() method is used to update a dictionary with the key-value pairs from another dictionary.

15). Which method returns a shallow copy of a dictionary?

a) copy()
b) clone()
c) duplicate()
d) replicate()

Corresct answer is: a) copy()
Explanation: The copy() method returns a shallow copy of a dictionary, creating a new dictionary with the same key-value pairs.

16). Which of the following is an immutable data type and can be used as a key in a dictionary?

a) List
b) Tuple
c) Set
d) Dictionary

Corresct answer is: b) Tuple
Explanation: Tuples are immutable data types and can be used as keys in a dictionary. Lists, sets, and dictionaries are mutable and cannot be used as keys.

17). Which method returns a new dictionary with keys and values swapped?

a) switch()
b) swap()
c) reverse()
d) reversed()

Corresct answer is: c) reverse()
Explanation: The reverse() method returns a new dictionary where the keys and values are swapped.

18). Which method can be used to create a dictionary from two lists, one containing keys and the other containing values?

a) dict()
b) create()
c) make()
d) generate()

Corresct answer is: a) dict()
Explanation: The dict() function can be used to create a dictionary from two lists, where one list contains keys and the other contains values.

19). Which method returns the minimum key in a dictionary?

a) min_key()
b) smallest_key()
c) min()
d) min_key()

Corresct answer is: c) min()
Explanation: The min() method returns the minimum key in a dictionary based on their natural ordering.

20). Which method returns the maximum value in a dictionary?

a) max_value()
b) largest_value()
c) max()
d) max_value()

Corresct answer is: c) max()
Explanation: The max() method returns the maximum value in a dictionary based on their natural ordering.

21). Which method is used to sort the keys in a dictionary in ascending order?

a) sort()
b) sort_keys()
c) sorted()
d) order()

Corresct answer is: b) sort_keys()
Explanation: The sort_keys() method is used to sort the keys in a dictionary in ascending order.

22). Which method is used to sort the values in a dictionary in ascending order?

a) sort_values()
b) sort()
c) sorted()
d) order_values()

Corresct answer is: a) sort_values()
Explanation: The sort_values() method is used to sort the values in a dictionary in ascending order.

23). Which method is used to reverse the order of the keys in a dictionary?

a) reverse_keys()
b) reverse()
c) reversed()
d) invert_keys()

Corresct answer is: c) reversed()
Explanation: The reversed() method returns a reversed view object for the keys in a dictionary.

24). Which method can be used to perform a shallow comparison between two dictionaries?

a) compare()
b) equals()
c) compare_dicts()
d) __eq__()

Corresct answer is: d) __eq__()
Explanation: The __eq__() method can be used to perform a shallow comparison between two dictionaries for equality.

25). Which method returns a hash value for a dictionary?

a) hash()
b) get_hash()
c) calculate_hash()
d) __hash__()

Corresct answer is: d) __hash__()
Explanation: The __hash__() method returns a hash value for a dictionary, allowing it to be used as a key in another dictionary or a member of a set.

Python Tuple MCQ : Set 4

Python Tuple MCQ

1). What is the output of the following code?

l = [(” “,), (‘a’, ‘b’), (‘a’, ‘b’, ‘c’), (‘d’,), ()]
print(“Original list of tuples: “, l)
for tup in l:
    if len(tup) == 0:
        l.remove(tup)
print(“After removing empty tuples: “, l)

a). Original list of tuples: [(” “,), (‘a’, ‘b’), (‘a’, ‘b’, ‘c’), (‘d’,), ()]
After removing empty tuples: [(” “,), (‘a’, ‘b’), (‘a’, ‘b’, ‘c’), (‘d’,)]
b). Original list of tuples: [(‘ ‘,), (‘a’, ‘b’), (‘a’, ‘b’, ‘c’), (‘d’,), ()]
After removing empty tuples: [(‘ ‘,), (‘a’, ‘b’), (‘a’, ‘b’, ‘c’), (‘d’,)]
c). Original list of tuples: [(” “,), (‘a’, ‘b’), (‘a’, ‘b’, ‘c’), (‘d’,), ()]
After removing empty tuples: [(” “,), (‘a’, ‘b’, ‘c’), (‘d’,)]
d). Original list of tuples: [(” “,), (‘a’, ‘b’), (‘a’, ‘b’, ‘c’), (‘d’,), ()]
After removing empty tuples: [(‘a’, ‘b’, ‘c’), (‘d’,)]

Corresct answer is: b). Original list of tuples: [(‘ ‘,), (‘a’, ‘b’), (‘a’, ‘b’, ‘c’), (‘d’,), ()]
After removing empty tuples: [(‘ ‘,), (‘a’, ‘b’), (‘a’, ‘b’, ‘c’), (‘d’,)]
Explanation: The code initializes a list `l` with five tuples. It then iterates over the elements of `l` and removes any tuple with a length of 0 (an empty tuple).

2). What is the output of the following code?

l = [(3, 5.6), (6, 2.3), (1, 1.8)]
print(“Original list of tuples: “, l)
l1 = sorted(l, key=lambda x: float(x[1]))
print(“After sorting: “, l1)

a). Original list of tuples: [(3, 5.6), (6, 2.3), (1, 1.8)]
After sorting: [(1, 1.8), (6, 2.3), (3, 5.6)]
b). Original list of tuples: [(3, 5.6), (6, 2.3), (1, 1.8)]
After sorting: [(3, 5.6), (6, 2.3), (1, 1.8)]
c). Original list of tuples: [(3, 5.6), (6, 2.3), (1, 1.8)]
After sorting: [(6, 2.3), (3, 5.6), (1, 1.8)]
d). Error: name ‘tup’ is not defined

Corresct answer is: a). Original list of tuples: [(3, 5.6), (6, 2.3), (1, 1.8)]
After sorting: [(1, 1.8), (6, 2.3), (3, 5.6)]
Explanation: The code defines a list of tuples l and then prints the original list. The sorted() function is used to sort the list of tuples based on the second element of each tuple using a lambda function. The sorted list is then printed).

3). What is the output of the following code?

l = [1, 6, 8, 5, (4, 6, 8, 0), 5, 4]
print(“Original list: “, l)
for val in l:
    if type(val) is tuple:
        print(f”Elements in the tuple {val}: “, len(val))
a). Original list: [1, 6, 8, 5, (4, 6, 8, 0), 5, 4]
b). Original list: [1, 6, 8, 5, (4, 6, 8, 0), 5, 4]  Elements in the tuple (4, 6, 8, 0): 4
c). Elements in the tuple (4, 6, 8, 0): 4
d). None of the above

Corresct answer is: b). Original list: [1, 6, 8, 5, (4, 6, 8, 0), 5, 4]  Elements in the tuple (4, 6, 8, 0): 4
Explanation: The code initializes a list l containing various elements, including a tuple (4, 6, 8, 0). The code then iterates over each element in the list. When it encounters a tuple element, it prints the message “Elements in the tuple (4, 6, 8, 0): 4”. 

4). What is the output of the following code?

tup = (5, 4, 3, 1)
print(“Original tuple: “, tup)
product = 1
for val in tup:
    product *= val
print(“Multiplication of elements in the tuple: “, product)

a). Original tuple: (5, 4, 3, 1), Multiplication of elements in the tuple: 120
b). Original tuple: (5, 4, 3, 1), Multiplication of elements in the tuple: 60
c). Original tuple: (5, 4, 3, 1), Multiplication of elements in the tuple: 20
d). Original tuple: (5, 4, 3, 1), Multiplication of elements in the tuple: 1

Corresct answer is: b). Original tuple: (5, 4, 3, 1), Multiplication of elements in the tuple: 60
Explanation: The code initializes a variable product to 1. It then iterates through each element in the tuple tup and multiplies it with the current value of product. The final value of product will be the multiplication of all the elements in the tuple, which is 60.

5). What is the output of the following code?

tup = (‘4563′, ’68’, ‘1’,)
print(“Original tuple: “, tup)
l = []
for val in tup:
    if type(val) is str:
        l.append(int(val))
tup = tuple(l)
print(“After converting to integers: “, tup)

a). Original tuple: (‘4563′, ’68’, ‘1’)
After converting to integers: (4563, 68, 1)
b). Original tuple: (‘4563′, ’68’, ‘1’)
After converting to integers: (‘4563′, ’68’, ‘1’)
c). Original tuple: (4563, 68, 1)
After converting to integers: (4563, 68, 1)
d). Original tuple: (4563, 68, 1)
After converting to integers: (‘4563′, ’68’, ‘1’)

Corresct answer is: a). Original tuple: (‘4563′, ’68’, ‘1’)
After converting to integers: (4563, 68, 1)
Explanation: The code iterates over each value in the tup tuple. If the value is of type string (str), it is converted to an integer using the int() function and appended to the list l. Finally, the list l is converted back to a tuple, resulting in (4563, 68, 1).

6). What is the output of the following code?

tup = (4, 5, 3, 8)
str1 = “”
print(“Original tuple: “, tup)
for val in tup:
    str1 += str(val)
num = int(str1)
print(“Integer: “, num)

a). Original tuple: (4, 5, 3, 8), Integer: 4538
b). Original tuple: (4, 5, 3, 8), Integer: 4583
c). Original tuple: (4, 5, 3, 8), Integer: 5438
d). Original tuple: (4, 5, 3, 8), Integer: 5384

Corresct answer is: a). Original tuple: (4, 5, 3, 8), Integer: 4538
Explanation: The code initializes an empty string `str1` and a tuple `tup` with values (4, 5, 3, 8). It then iterates over each element in the tuple using a loop. In each iteration, the current element is converted to a string and concatenated with `str1`. After the loop, `str1` becomes “4538”. The string `str1` is then converted to an integer `num` using the `int()` function. 

7). What is the output of the following code?

a = (1, 6, 7)
b = (4, 3, 0)
c = (2, 6, 8)
print(f”Original tuples: {a},{b},{c}”)
s1 = map(sum, zip(a,b,c))
result = tuple(s1)
print(“Element wise sum of the given tuples: “,result)

a). Original tuples: (1, 6, 7), (4, 3, 0), (2, 6, 8)
Element wise sum of the given tuples: (7, 15, 15)
b). Original tuples: (1, 6, 7), (4, 3, 0), (2, 6, 8)
Element wise sum of the given tuples: (7, 15, 15, 0)
c). Original tuples: (1, 6, 7), (4, 3, 0), (2, 6, 8)
Element wise sum of the given tuples: (6, 15, 15)
d). Original tuples: (1, 6, 7), (4, 3, 0), (2, 6, 8)
Element wise sum of the given tuples: (7, 12, 15)

Corresct answer is: a). Original tuples: (1, 6, 7), (4, 3, 0), (2, 6, 8)
Element wise sum of the given tuples: (7, 15, 15)
Explanation: The code first defines three tuples: a = (1, 6, 7), b = (4, 3, 0), and c = (2, 6, 8). It then prints the original tuples using f-string formatting. The zip() function is used to combine the corresponding elements of the tuples, and the map() function with sum as the first argument is used to calculate the sum of each group of corresponding elements. The map object is converted to a tuple using tuple(), and the result is stored in the variable result. Finally, the element-wise sum of the tuples is printed, resulting in (7, 15, 15).

8). What is the output of the following code?

l = [(1, 5), (7, 8), (4, 0)]
l1 = []
print(“Original list: “, l)
for tup in l:
    l1.append(list(tup))
print(“After converting tuples inside a list to list: “, l1)

a). Original list: [(1, 5), (7, 8), (4, 0)]
After converting tuples inside a list to list: [[1, 5], [7, 8], [4, 0]]
b). Original list: [(1, 5), (7, 8), (4, 0)]
After converting tuples inside a list to list: [(1, 5), (7, 8), (4, 0)]
c). Original list: [1, 5, 7, 8, 4, 0]
After converting tuples inside a list to list: [1, 5, 7, 8, 4, 0]
d). Error: Cannot convert tuples to lists

Corresct answer is: a). Original list: [(1, 5), (7, 8), (4, 0)]
After converting tuples inside a list to list: [[1, 5], [7, 8], [4, 0]]
Explanation: The code starts with a list `l` containing tuples. The loop iterates over each tuple `tup` in `l` and converts each tuple into a list using the `list()` function. The converted lists are appended to a new list `l1`. The output will be the original list `l` followed by the modified list `l1`, where the tuples have been converted to lists.

9). What is the output of the following code?

l = [(1, 7), (-4, -5), (0, 6), (-1, 3)]
for tup in l:
if any(ele < 0 for ele in tup):
print(“Tuple having negative element: “, tup)
a). Tuple having negative element: (1, 7), Tuple having negative element: (0, 6)
b). Tuple having negative element: (-4, -5), Tuple having negative element: (-1, 3)
c). Tuple having negative element: (-1, 3)
d). Tuple having negative element: (0, 6), Tuple having negative element: (1, 7)

Corresct answer is: b). Tuple having negative element: (-4, -5), Tuple having negative element: (-1, 3)
Explanation: The code iterates over each tuple in the list l. The any() function checks if any element in the tuple is less than 0. Since the tuple (-4, -5), (-1, 3) has negative elements, it will be printed as “Tuple having negative element: (-4, -5), Tuple having negative element: (-1, 3)”.

10). What is the output of the following code?

tup = (6, 4, 9, 0, 2, 6, 1, 3, 4)
print(“Original tuple: “, tup)
new_tup = tuple(set(tup))
print(“New tuple: “, new_tup)

a). Original tuple: (6, 4, 9, 0, 2, 6, 1, 3, 4) New tuple: (6, 4, 9, 0, 2, 6, 1, 3)
b). Original tuple: (6, 4, 9, 0, 2, 6, 1, 3, 4) New tuple: (6, 4, 9, 0, 2, 1, 3)
c). Original tuple: (6, 4, 9, 0, 2, 6, 1, 3, 4) New tuple: (0, 1, 2, 3, 4, 6, 9)
d). Original tuple: (6, 4, 9, 0, 2, 6, 1, 3, 4) New tuple: (4, 6, 9, 0, 2, 1, 3)

Corresct answer is: c). Original tuple: (6, 4, 9, 0, 2, 6, 1, 3, 4) New tuple: (0, 1, 2, 3, 4, 6, 9)
Explanation: In the given code, the original tuple `tup` is created with elements (6, 4, 9, 0, 2, 6, 1, 3, 4). The `set()` function is used to convert the tuple into a set, which removes the duplicate elements. Then, the `tuple()` function is used to convert the set back into a tuple. The output will be “Original tuple: (6, 4, 9, 0, 2, 6, 1, 3, 4)” and “New tuple: (0, 1, 2, 3, 4, 6, 9)”.

11). What is the output of the following code?

l = [(4,8,3),(3,4,0),(1,6,2)]
print(“Original list of tuples: “,l)
i = 1
product = 1
for tup in l:
    for ele in tup:
        if tup.index(ele) == i:
            product *= ele
print(f”Product of {i} element in each tuple is {product}”)

a). Original list of tuples: [(4,8,3),(3,4,0),(1,6,2)]
Product of 1 element in each tuple is 56
b). Original list of tuples: [(4,8,3),(3,4,0),(1,6,2)]
Product of 1 element in each tuple is 180
c). Original list of tuples: [(4,8,3),(3,4,0),(1,6,2)]
Product of 1 element in each tuple is 192
d). Original list of tuples: [(4,8,3),(3,4,0),(1,6,2)]
Product of 1 element in each tuple is 12

Corresct answer is: c). Original list of tuples: [(4,8,3),(3,4,0),(1,6,2)]
Product of 1 element in each tuple is 192
Explanation: The code calculates the product of the element at index 1 in each tuple. The elements at index 1 in the given list of tuples are 8, 4, and 6. The product of these elements is 8 * 4 * 6 = 192.

12). What is the output of the following code?

l = [(‘s’,’q’,’a’),(‘t’,’o’),(‘o’,’l’,’s’)]
print(“Original list of tuples: “, l)
str1 = “”
for tup in l:
    for char in tup:
        str1 += char + ” “
print(“New string: “, str1)

a). Original list of tuples: [(‘s’,’q’,’a’),(‘t’,’o’),(‘o’,’l’,’s’)]
New string: “s q a t o o l s”
b). Original list of tuples: [(‘s’,’q’,’a’),(‘t’,’o’),(‘o’,’l’,’s’)]
New string: “sqa to ols”
c). Original list of tuples: [(‘s’,’q’,’a’),(‘t’,’o’),(‘o’,’l’,’s’)]
New string: “sqa tols”
d). Original list of tuples: [(‘s’,’q’,’a’),(‘t’,’o’),(‘o’,’l’,’s’)]
New string: “s q a t o l s”

Corresct answer is: a). Original list of tuples: [(‘s’,’q’,’a’),(‘t’,’o’),(‘o’,’l’,’s’)]
New string: “s q a t o o l s”
Explanation: The code snippet initializes a list of tuples `l`. It then iterates over each tuple in `l` and concatenates each character from the tuples into a string `str1`, separating them with a space. The output will be “Original list of tuples: [(‘s’,’q’,’a’),(‘t’,’o’),(‘o’,’l’,’s’)]” and “New string: “s q a t o o l s”.

13). What is the output of the following code?

a = (1, 2, 3, 4)
print(“Tuple: “, a)
b = ‘sqatools’
print(“String: “, b)
l = []
for ele in a:
    l.append(ele)
    l.append(b)
print(“New list: “, l)

a). Tuple: (1, 2, 3, 4), String: ‘sqatools’, New list: [1, ‘sqatools’, 2, ‘sqatools’, 3, ‘sqatools’, 4, ‘sqatools’]
b). Tuple: (1, 2, 3, 4), String: ‘sqatools’, New list: [1, 2, 3, 4, ‘sqatools’]
c). Tuple: (1, 2, 3, 4), String: ‘sqatools’, New list: [1, 2, 3, 4]
d). Error: ‘str’ object has no attribute ‘append’

Corresct answer is: a). Tuple: (1, 2, 3, 4), String: ‘sqatools’, New list: [1, ‘sqatools’, 2, ‘sqatools’, 3, ‘sqatools’, 4, ‘sqatools’]
Explanation: The code snippet initializes a tuple a with values (1, 2, 3, 4) and a string b with the value ‘sqatools’. It then creates an empty list l. The subsequent for loop iterates over each element in the tuple a). For each element, it appends the element itself (ele) and the string b to the list l.

14). What is the output of the following code?

l = [[‘sqatools’], [‘is’], [‘best’]]
print(“List of lists: “, l)
l1 = []
for lists in l:
    l1.append(tuple(lists))
tup = tuple(l1)
print(“Tuple of list of lists: “, tup)

a). List of lists: [[‘sqatools’], [‘is’], [‘best’]]
Tuple of list of lists: ((‘sqatools’,), (‘is’,), (‘best’,))
b). List of lists: [[‘sqatools’], [‘is’], [‘best’]]
Tuple of list of lists: ([‘sqatools’], [‘is’], [‘best’])
c). List of lists: [[‘sqatools’], [‘is’], [‘best’]]
Tuple of list of lists: ((‘sqatools’,), (‘is’,), (‘best’,))
d). Error: cannot convert list to tuple

Corresct answer is: a). List of lists: [[‘sqatools’], [‘is’], [‘best’]]
Tuple of list of lists: ((‘sqatools’,), (‘is’,), (‘best’,))
Explanation: The code starts with a list of lists, l, which contains three inner lists. Each inner list is converted into a tuple using the tuple() function and appended to a new list, l1. Finally, l1 is converted into a tuple, tup. The output will be “List of lists: [[‘sqatools’], [‘is’], [‘best’]]” and “Tuple of list of lists: ((‘sqatools’,), (‘is’,), (‘best’,))”.

15). What is the output of the following code?

tup = (56, 99)
str1 = “”
result = float(‘.’.join(str(ele) for ele in tup))
print(“Float number: “, result)

a). Float number: 56.99
b). Float number: 56.0
c). Float number: 0.5699
d). Error: unsupported operand type(s) for .join(): ‘float’ and ‘str’

Corresct answer is: a
Explanation: The code snippet converts the tuple (56, 99) into a float number by joining the elements with a dot using ‘.’.join() and then converting the resulting string to a float using float(). The resulting float number will be 56.99, and it will be printed as “Float number: 56.99”.

16). What is the output of the following code?

l = [(‘a’, ‘b’), (‘d’, ‘e’), (‘b’, ‘a’)]
print(“Original list of tuples: “, l)
temp = set(l) & {(b, a) for a, b in l}
sym = {(a, b) for a, b in temp if a < b}
print(“Tuples that are symmetric: “, sym)

a). Original list of tuples: [(‘a’, ‘b’), (‘d’, ‘e’), (‘b’, ‘a’)]
Tuples that are symmetric: {(‘a’, ‘b’), (‘b’, ‘a’)}
b). Original list of tuples: [(‘a’, ‘b’), (‘d’, ‘e’), (‘b’, ‘a’)]
Tuples that are symmetric: {(‘a’, ‘b’)}
c). Original list of tuples: [(‘a’, ‘b’), (‘d’, ‘e’), (‘b’, ‘a’)]
Tuples that are symmetric: {(‘b’, ‘a’)}
d). Original list of tuples: [(‘a’, ‘b’), (‘d’, ‘e’), (‘b’, ‘a’)]
Tuples that are symmetric: {}

Corresct answer is: b). Original list of tuples: [(‘a’, ‘b’), (‘d’, ‘e’), (‘b’, ‘a’)]
Tuples that are symmetric: {(‘a’, ‘b’)}
Explanation: The original list of tuples is [(‘a’, ‘b’), (‘d’, ‘e’), (‘b’, ‘a’)]. The code uses set operations and set comprehension to find the symmetric tuples. The symmetric tuples are (‘a’, ‘b’) and (‘b’, ‘a’). Thus, the output will be “Original list of tuples: [(‘a’, ‘b’), (‘d’, ‘e’), (‘b’, ‘a’)] Tuples that are symmetric: {(‘a’, ‘b’)}.”

17). What is the output of the following code?

tup = (‘s’, ‘q’, ‘a’, (‘t’, ‘o’, ‘o’, ‘l’, ‘s’), ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’)
print(“Original tuple: “, tup)
l = []
for char in tup:
    if type(char) != tuple:
        l.append(char)
new = tuple(l)
print(“New tuple: “, new)

a). Original tuple: (‘s’, ‘q’, ‘a’, (‘t’, ‘o’, ‘o’, ‘l’, ‘s’), ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’)
New tuple: (‘s’, ‘q’, ‘a’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’)
b). Original tuple: (‘s’, ‘q’, ‘a’, (‘t’, ‘o’, ‘o’, ‘l’, ‘s’), ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’)
New tuple: (‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’, ‘s’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’)
c). Original tuple: (‘s’, ‘q’, ‘a’, (‘t’, ‘o’, ‘o’, ‘l’, ‘s’), ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’)
New tuple: (‘s’, ‘q’, ‘a’, (‘t’, ‘o’, ‘o’, ‘l’, ‘s’), ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’)
d). Error: tuple’ object has no attribute ‘append’

Corresct answer is: a). Original tuple: (‘s’, ‘q’, ‘a’, (‘t’, ‘o’, ‘o’, ‘l’, ‘s’), ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’)
New tuple: (‘s’, ‘q’, ‘a’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’)
Explanation: The code iterates through each element in the original tuple `tup` and checks if it is a tuple or not. If it is not a tuple, the element is appended to the list `l`. Finally, the list `l` is converted back to a tuple `new`. The output will be “Original tuple: (‘s’, ‘q’, ‘a’, (‘t’, ‘o’, ‘o’, ‘l’, ‘s’), ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’)” and “New tuple: (‘s’, ‘q’, ‘a’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’)”. The inner tuple `(‘t’, ‘o’, ‘o’, ‘l’, ‘s’)` is not included in the new tuple, as only individual non-tuple elements are added to the list `l`.

18). What is the output of the following code?

l = [(1, 5, 7), (3, 4, 2), (4, 9, 0)]
print(“Original list of tuples: “, l)
l1 = sorted(l, key=lambda x: max(x), reverse=True)
print(“After sorting: “, l1)

a). Original list of tuples: [(1, 5, 7), (3, 4, 2), (4, 9, 0)]
After sorting: [(4, 9, 0), (1, 5, 7), (3, 4, 2)]
b). Original list of tuples: [(1, 5, 7), (3, 4, 2), (4, 9, 0)]
After sorting: [(1, 5, 7), (3, 4, 2), (4, 9, 0)]
c). Original list of tuples: [(1, 5, 7), (3, 4, 2), (4, 9, 0)]
After sorting: [(4, 9, 0), (3, 4, 2), (1, 5, 7)]
d). Original list of tuples: [(4, 9, 0), (3, 4, 2), (1, 5, 7)]
After sorting: [(4, 9, 0), (3, 4, 2), (1, 5, 7)]

Corresct answer is: a). Original list of tuples: [(1, 5, 7), (3, 4, 2), (4, 9, 0)]
After sorting: [(4, 9, 0), (1, 5, 7), (3, 4, 2)]
Explanation: The original list of tuples is [(1, 5, 7), (3, 4, 2), (4, 9, 0)]. The sorting is based on the maximum value in each tuple, in descending order. After sorting, the list becomes [(4, 9, 0), (1, 5, 7), (3, 4, 2)] where the tuple with the maximum value of 9 is placed first, followed by tuples with values 7, 5, 4, 3, and 2.

19). What is the output of the following code?

tup1 = (‘s’, ‘q’, ‘a’)
tup2 = (‘t’, ‘o’, ‘o’, ‘l’)
print(f”Original tuple: {tup1} {tup2}”)
result = tup1 + tup2
print(“Combined tuple: “, result)

a). Original tuple: (‘s’, ‘q’, ‘a’) (‘t’, ‘o’, ‘o’, ‘l’)
Combined tuple: (‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’)
b). Original tuple: (‘s’, ‘q’, ‘a’) (‘t’, ‘o’, ‘o’, ‘l’)
Combined tuple: (‘s’, ‘q’, ‘a’, ‘tool’)
c). Original tuple: (‘s’, ‘q’, ‘a’) (‘t’, ‘o’, ‘o’, ‘l’)
Combined tuple: (‘tool’, ‘s’, ‘q’, ‘a’)
d). Original tuple: (‘t’, ‘o’, ‘o’, ‘l’) (‘s’, ‘q’, ‘a’)
Combined tuple: (‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’)

Corresct answer is: a). Original tuple: (‘s’, ‘q’, ‘a’) (‘t’, ‘o’, ‘o’, ‘l’)
Combined tuple: (‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’)
Explanation: The code concatenates `tup1` and `tup2` using the `+` operator, resulting in a combined tuple `(‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’)`. The original tuples are printed as `(‘s’, ‘q’, ‘a’)` and `(‘t’, ‘o’, ‘o’, ‘l’)`, respectively, and the combined tuple is printed as `(‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’)`.

20). What is the output of the following code?

tup1 = [(1, 5), (4, 8), (3, 9)]
tup2 = [(3, 9), (5, 6), (1, 5), (0, 4)]
print(f”Tuples: {tup1} and {tup2}”)
result = (set(tup1) & set(tup2))
print(“Common elements between tuples: “, result)

a). Tuples: [(1, 5), (4, 8), (3, 9)] and [(3, 9), (5, 6), (1, 5), (0, 4)]
Common elements between tuples: [(1, 5), (5, 6)]
b). Tuples: [(1, 5), (4, 8), (3, 9)] and [(3, 9), (5, 6), (1, 5), (0, 4)]
Common elements between tuples: {(1, 5), (3, 9)}
c). Tuples: [(1, 5), (4, 8), (3, 9)] and [(3, 9), (5, 6), (1, 5), (0, 4)]
Common elements between tuples: [(3, 9), (0, 4)]
d). Tuples: [(1, 5), (4, 8), (3, 9)] and [(3, 9), (5, 6), (1, 5), (0, 4)]
Common elements between tuples: {(3, 9), (3, 9)}

Corresct answer is: b). Tuples: [(1, 5), (4, 8), (3, 9)] and [(3, 9), (5, 6), (1, 5), (0, 4)]
Common elements between tuples: {(1, 5), (3, 9)}
Explanation: The code defines two lists of tuples, `tup1` and `tup2`, and prints their values. The `&` operator is used to find the common elements between the two sets created from `tup1` and `tup2`. The resulting common elements are of type set and will be printed as `{(1, 5), (3, 9)}`.

21). What is the output of the following code?

l = [(8, 9), (4, 7), (3, 6), (8, 9)]
print(“Original list of tuples: “, l)
print(“Total number of unique tuples: “, len(set(l)))

a). Original list of tuples: [(8, 9), (4, 7), (3, 6), (8, 9)]
Total number of unique tuples: 3
b). Original list of tuples: [(8, 9), (4, 7), (3, 6), (8, 9)]
Total number of unique tuples: 4
c). Original list of tuples: [(8, 9), (4, 7), (3, 6), (8, 9)]
Total number of unique tuples: 2
d). Original list of tuples: [(8, 9), (4, 7), (3, 6), (8, 9)]
Total number of unique tuples: 1

Corresct answer is: a). Original list of tuples: [(8, 9), (4, 7), (3, 6), (8, 9)]
Total number of unique tuples: 3
Explanation: The code first prints the original list of tuples, which is [(8, 9), (4, 7), (3, 6), (8, 9)]. Then it uses the set() function to convert the list to a set, which removes the duplicate tuples. The length of the set is then printed, which is 2. Therefore, the output is “Original list of tuples: [(8, 9), (4, 7), (3, 6), (8, 9)] Total number of unique tuples: 3”.

22). What is the output of the following code?

tup = (5, 3, 9, 6)
print(“Original tuple: “, tup)
add = 0
for ele in tup:
    add += ele
print(“Average of elements in the tuple: “, add/len(tup))

a). Original tuple: (5, 3, 9, 6), Average of elements in the tuple: 5.75
b). Original tuple: (5, 3, 9, 6), Average of elements in the tuple: 6.25
c). Original tuple: (5, 3, 9, 6), Average of elements in the tuple: 6
d). Error: unsupported operand type(s) for /: ‘int’ and ‘tuple’

Corresct answer is: a). Original tuple: (5, 3, 9, 6), Average of elements in the tuple: 5.75
Explanation: The code initializes a tuple tup with values (5, 3, 9, 6). It then calculates the sum of all elements using a loop and stores it in the variable add). The average is calculated by dividing the sum add by the length of the tuple using the len() function. The output will be “Original tuple: (5, 3, 9, 6), Average of elements in the tuple: 5.75”.

23). What is the output of the following code?

A = (7, 4, 9)
B = (3,)
print(f”tuple1: {A}, tuple2: {B}”)
A, B = B, A
print(f”tuple1: {A}, tuple2: {B}”)

a). tuple1: (7, 4, 9), tuple2: (3,)
tuple1: (3,), tuple2: (7, 4, 9)
b). tuple1: (7, 4, 9), tuple2: (3,)
tuple1: (7, 4, 9), tuple2: (3,)
c). tuple1: (7, 4, 9), tuple2: (3,)
tuple1: (3,), tuple2: (7, 4, 9)
d). tuple1: (3,), tuple2: (7, 4, 9)
tuple1: (3,), tuple2: (7, 4, 9)

Corresct answer is: c). tuple1: (7, 4, 9), tuple2: (3,)
tuple1: (3,), tuple2: (7, 4, 9)
Explanation: In the code, tuple A is initially `(7, 4, 9)` and tuple B is `(3,)`. When the line `A, B = B, A` is executed, the values of A and B are swapped). Now A becomes `(3,)` and B becomes `(7, 4, 9)`. The first print statement outputs `tuple1: (7, 4, 9), tuple2: (3,)` because it is executed before the swap. The second print statement outputs `tuple1: (3,), tuple2: (7, 4, 9)` after the swap.

24). What is the output of the following code?

tup = (7, 4, 9, 2, 0)
if type(tup) == tuple:
    print(“True”)
else:
    print(“False”)

a). True
b). False
c). Error: invalid syntax
d). Error: unsupported operand type(s) for ==

Corresct answer is: a). True
Explanation: The code snippet checks whether the variable tup is of type tuple using the type() function. Since tup is indeed a tuple, the condition is True, and the code will print “True” as the output.

25). What is the output of the following code?

tup = (‘p’,’y’,’t’,’h’,’o’,’n’)
print(“Original tuple: “,tup)
print(“Last element of the tuple using negative indexing: “,tup[-1])

a). Original tuple: (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
Last element of the tuple using negative indexing: ‘p’
b). Original tuple: (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
Last element of the tuple using negative indexing: ‘n’
c). Original tuple: (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
Last element of the tuple using negative indexing: ‘o’
d). Original tuple: (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
Last element of the tuple using negative indexing: ‘t’

Corresct answer is: b). Original tuple: (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
Last element of the tuple using negative indexing: ‘n’
Explanation: The original tuple is `(‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)`. Negative indexing allows accessing elements from the end of the tuple. `-1` represents the last element of the tuple. Therefore, the output will be “Last element of the tuple using negative indexing: ‘n'”.

Python Tuple MCQ : Set 3

Python Tuple MCQ

1). What is the output of the following code?

tup = (‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’, ‘s’)
str1 = ”
for char in tup:
    str1 += char
print(“String: “, str1)

a). String: ‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’, ‘s’
b). String: ‘sqltools’
c). String: ‘sqa’
d). Error: tuple object has no attribute ‘+’

Corresct answer is: b). String: ‘sqltools’
Explanation: The code iterates over each character in the tuple tup and concatenates them to the str1 variable. After the loop completes, str1 will contain the string ‘sqltools’, which is printed as the output.

2). What is the output of the following code?

tup = (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
if ‘p’ in tup:
    print(“True”)
else:
    print(“False”)

a). True
b). False
c). Error: ‘p’ is not in tup
d). Error: invalid syntax

Corresct answer is: a). True
Explanation: The code checks if the element ‘p’ is present in the tuple tup using the in operator. Since ‘p’ is indeed present in the tuple, the condition is true, and the output will be “True”.

3). What is the output of the following code?

list1 = [12, 67]
tup = (6, 8, 4)
result = tuple(list(tup) + list1)
print(result)

a). (6, 8, 4, 12, 67)
b). (6, 8, 4, [12, 67])
c). (6, 8, 4, (12, 67))
d). Error: cannot concatenate ‘tuple’ and ‘list’ objects

Corresct answer is: a). (6, 8, 4, 12, 67)
Explanation: In the given code, list(tup) converts the tuple tup into a list, resulting in [6, 8, 4]. Similarly, list1 is already a list with values [12, 67]. Using the + operator concatenates the two lists, resulting in [6, 8, 4, 12, 67]. Finally, tuple() converts the concatenated list back into a tuple, resulting in (6, 8, 4, 12, 67). 

4). What is the output of the following code?

tup = (4, 6, 2)
print(“Sum of elements in the tuple: “, sum(tup))

a). Sum of elements in the tuple: 12
b). Sum of elements in the tuple: 10
c). Sum of elements in the tuple: (4, 6, 2)
d). Error: ‘tuple’ object has no attribute ‘sum’

Corresct answer is: a). Sum of elements in the tuple: 12
Explanation: The code initializes a tuple tup with the values (4, 6, 2). The sum() function is then used to calculate the sum of all the elements in the tuple. The output statement prints “Sum of elements in the tuple: ” followed by the calculated sum, which is 12. 

5). What is the output of the following code?

tup = (1, 3, 5, 7, 6)
print(“Original tuple: “, tup)
a = list(tup)
for i in a:
    j = a).index(i)
    b = i ** 2
    a[j] = b
tup = tuple(a)
print(“After squaring elements: “, tup)

a). Original tuple: (1, 3, 5, 7, 6), After squaring elements: (1, 9, 25, 49, 36)
b). Original tuple: (1, 3, 5, 7, 6), After squaring elements: (1, 9, 25, 49, 6)
c). Original tuple: (1, 3, 5, 7, 6), After squaring elements: (1, 3, 5, 7, 6)
d). Error: ‘tuple’ object has no attribute ‘index’

Corresct answer is: b). Original tuple: (1, 3, 5, 7, 6), After squaring elements: (1, 9, 25, 49, 6)
Explanation: The code starts with the tuple `tup` containing the values (1, 3, 5, 7, 6). It converts the tuple to a list `a` using the `list()` function. Then, it iterates over each element `i` in the list and calculates its square `b`. The square value is assigned back to the list at index `j` using the `index()` method). Finally, the list is converted back to a tuple `tup` using the `tuple()` function.

6). What is the output of the following code?

tup = (1, 2, 3, 4)
list1 = []
for a, b in zip(tup, tup[1:]):
    c = a * b
    list1.append(c)
tup = tuple(list1)
print(“Multiplying adjacent elements: “, tup)

a). Multiplying adjacent elements: (2, 6, 12)
b). Multiplying adjacent elements: (1, 4, 9, 16)
c). Multiplying adjacent elements: (1, 2, 3, 4)
d). Multiplying adjacent elements: []

Corresct answer is: a). Multiplying adjacent elements: (2, 6, 12)
Explanation: The code iterates over tup and tup[1:] simultaneously using the zip() function. It multiplies the adjacent elements and appends the result to list1. Finally, list1 is converted back to a tuple and assigned to tup. The output will be “Multiplying adjacent elements: (2, 6, 12)”, as the adjacent elements are multiplied).

7). What is the output of the following code?

list1 = [12, 65, 34, 77]
list2 = []
for ele in list1:
    a = 2 * ele
    list2.append(a)

tup = tuple(list2)
print(“Original list: “, list1)
print(“After multiplying by 2: “, tup)

a). Original list: [12, 65, 34, 77], After multiplying by 2: (24, 130, 68, 154)
b). Original list: [12, 65, 34, 77], After multiplying by 2: [24, 130, 68, 154]
c). Original list: [12, 65, 34, 77], After multiplying by 2: (12, 65, 34, 77)
d). Error: invalid syntax

Corresct answer is: a). Original list: [12, 65, 34, 77], After multiplying by 2: (24, 130, 68, 154)
Explanation: The code initializes an empty list list2 and iterates over each element ele in list1. It multiplies each element by 2 and appends the result to list2. Then, the code converts list2 to a tuple tup. The output will be “Original list: [12, 65, 34, 77]” and “After multiplying by 2: (24, 130, 68, 154)”.

8). What is the output of the following code?

tup = (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
print(“Original tuple: “, tup)
l = list(tup)
l.remove(‘h’)
tup = tuple(l)
print(“After removing an element: “, tup)


a). Original tuple: (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
After removing an element: (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
b). Original tuple: (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
After removing an element: (‘p’, ‘y’, ‘t’, ‘o’, ‘n’)
c). Original tuple: (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
After removing an element: (‘p’, ‘y’, ‘t’, ‘n’)
d). Original tuple: (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
After removing an element: (‘p’, ‘y’, ‘o’, ‘n’)

Corresct answer is: c). Original tuple: (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
After removing an element: (‘p’, ‘y’, ‘t’, ‘n’)
Explanation: The code converts the tuple `tup` into a list, removes the element `’h’` from the list, and then converts it back to a tuple. The output will be `(‘p’, ‘y’, ‘t’, ‘n’)`.

9). What is the output of the following code?

tup = (‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’, ‘s’)
print(“Index of a: “, tup.index(‘a’))

a). Index of a: 2
b). Index of a: 3
c). Index of a: 6
d). Error: ‘a’ is not in tuple ‘tup’

Corresct answer is: a). Index of a: 2
Explanation: The code defines a tuple tup with the elements ‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’, ‘s’. The index() method is used to find the index of the first occurrence of the element ‘a’ in the tuple. Since ‘a’ is at index 2, the output will be “Index of a: 2”.

10). What is the output of the following code?

tup = (‘v’, ‘i’, ‘r’, ‘a’, ‘t’)
print(“Original tuple: “, tup)
print(“Length of the tuple: “, len(tup))

a). Original tuple: (‘v’, ‘i’, ‘r’, ‘a’, ‘t’) Length of the tuple: 5
b). Original tuple: v i r a t Length of the tuple: 5
c). Original tuple: (‘v’, ‘i’, ‘r’, ‘a’, ‘t’) Length of the tuple: 1
d). Original tuple: v i r a t Length of the tuple: 1

Corresct answer is: a). Original tuple: (‘v’, ‘i’, ‘r’, ‘a’, ‘t’) Length of the tuple: 5
Explanation: The code defines a tuple tup with elements ‘v’, ‘i’, ‘r’, ‘a’, and ‘t’. The first print() statement outputs the original tuple as (‘v’, ‘i’, ‘r’, ‘a’, ‘t’), and the second print() statement outputs the length of the tuple, which is 5.

11). What is the output of the following code?

tup = ((5, ‘s’), (6, ‘l’))
print(“Tuple: “, tup)
D = dict(tup)
print(“Dictionary: “, D)

a). Tuple: ((5, ‘s’), (6, ‘l’))
Dictionary: {5: ‘s’, 6: ‘l’}
b). Tuple: [(5, ‘s’), (6, ‘l’)]
Dictionary: {5: ‘s’, 6: ‘l’}
c). Tuple: ((5, ‘s’), (6, ‘l’))
Dictionary: {(5, ‘s’): (6, ‘l’)}
d). Tuple: [(5, ‘s’), (6, ‘l’)]
Dictionary: {(5, ‘s’): (6, ‘l’)}

Corresct answer is: a). Tuple: ((5, ‘s’), (6, ‘l’))
Dictionary: {5: ‘s’, 6: ‘l’}
Explanation: The code first initializes a tuple `tup` containing two inner tuples. Printing the `tup` variable will output `((5, ‘s’), (6, ‘l’))`. Then, the `dict()` function is used to convert the tuple `tup` into a dictionary `D`. The output of `D` will be `{5: ‘s’, 6: ‘l’}`, where the first element of each inner tuple becomes a key, and the second element becomes its corresponding value in the dictionary.

12). What is the output of the following code?

list1 = [(3, 4), (6, 2), (8, 9)]
print(“List: “, list1)
print(“Tuple: “, list(zip(*list1)))

a). List: [(3, 4), (6, 2), (8, 9)]
Tuple: [(3, 6, 8), (4, 2, 9)]
b). List: [(3, 4), (6, 2), (8, 9)]
Tuple: [(4, 2, 9), (3, 6, 8)]
c). List: [(3, 6, 8), (4, 2, 9)]
Tuple: [(3, 4), (6, 2), (8, 9)]
d). List: [(4, 2, 9), (3, 6, 8)]
Tuple: [(3, 4), (6, 2), (8, 9)]

Corresct answer is: a). List: [(3, 4), (6, 2), (8, 9)]
Tuple: [(3, 6, 8), (4, 2, 9)]
Explanation: The code uses the zip() function with the unpacking operator * on the list list1. The zip() function takes the elements from each tuple in list1 and groups them together. The * operator is used to unpack the list of tuples. So, list(zip(*list1)) will result in [(3, 6, 8), (4, 2, 9)], which is a list of tuples where each tuple contains the corresponding elements from the original tuples.

13). What is the output of the following code?

tup = (4, 6, 8, 3, 1)
print(“Original tuple: “, tup)
tup1 = tuple(reversed(tup))
print(“Reversed tuple: “, tup1)

a). Original tuple: (4, 6, 8, 3, 1), Reversed tuple: (1, 3, 8, 6, 4)
b). Original tuple: (1, 3, 8, 6, 4), Reversed tuple: (4, 6, 8, 3, 1)
c). Original tuple: (4, 6, 8, 3, 1), Reversed tuple: (4, 6, 8, 3, 1)
d). Original tuple: (1, 3, 8, 6, 4), Reversed tuple: (1, 3, 8, 6, 4)

Corresct answer is: a). Original tuple: (4, 6, 8, 3, 1), Reversed tuple: (1, 3, 8, 6, 4)
Explanation: The original tuple is `(4, 6, 8, 3, 1)`. The `reversed()` function returns an iterator that yields the items of the tuple in reverse order. Converting the iterator to a tuple using `tuple()` will give the reversed tuple `(1, 3, 8, 6, 4)`. The code then prints the original tuple and the reversed tuple, resulting in the output “Original tuple: (4, 6, 8, 3, 1), Reversed tuple: (1, 3, 8, 6, 4)”.

14). What is the output of the following code?

l = [(‘s’,2),(‘q’,1),(‘a’,1),(‘s’,3),(‘q’,2),(‘a’,4)]
print(“List of tuples: “,l)
D = {}
for a, b in l:
    D.setdefault(a, []).append(b)
print(“Dictionary: “,D)

a). List of tuples: [(‘s’,2),(‘q’,1),(‘a’,1),(‘s’,3),(‘q’,2),(‘a’,4)]
Dictionary: {‘s’: [2, 3], ‘q’: [1, 2], ‘a’: [1, 4]}
b). List of tuples: [(‘s’,2),(‘q’,1),(‘a’,1),(‘s’,3),(‘q’,2),(‘a’,4)]
Dictionary: {‘s’: [3, 2], ‘q’: [2, 1], ‘a’: [4, 1]}
c). List of tuples: [(‘s’,2),(‘q’,1),(‘a’,1),(‘s’,3),(‘q’,2),(‘a’,4)]
Dictionary: {‘s’: [2, 3], ‘q’: [2, 1], ‘a’: [4, 1]}
d). List of tuples: [(‘s’,2),(‘q’,1),(‘a’,1),(‘s’,3),(‘q’,2),(‘a’,4)]
Dictionary: {‘s’: [3, 2], ‘q’: [1, 2], ‘a’: [1, 4]}

Corresct answer is: a). List of tuples: [(‘s’,2),(‘q’,1),(‘a’,1),(‘s’,3),(‘q’,2),(‘a’,4)]
Dictionary: {‘s’: [2, 3], ‘q’: [1, 2], ‘a’: [1, 4]}
Explanation: The code initializes an empty dictionary D and iterates through the tuples in the list l. For each tuple (a, b), it uses the setdefault() method to create a new key a in the dictionary if it doesn’t exist and appends b to the corresponding value list. The resulting dictionary will be {‘s’: [2, 3], ‘q’: [1, 2], ‘a’: [1, 4]}.

15). What is the output of the following code?

list1 = [(2,5,7),(3,4),(8,9,0,5)]
print(“Original list: “, list1)
for tup in list1:
    if len(tup) == 2:
        list1.remove(tup)

print(“After removing tuple having length 2: “, list1)

a). Original list: [(2,5,7),(3,4),(8,9,0,5)]
After removing tuple having length 2: [(2,5,7),(3,4),(8,9,0,5)]
b). Original list: [(2,5,7),(3,4),(8,9,0,5)]
After removing tuple having length 2: [(3,4),(8,9,0,5)]
c). Original list: [(2,5,7),(3,4),(8,9,0,5)]
After removing tuple having length 2: [(2,5,7),(8,9,0,5)]
d). Original list: [(2,5,7),(3,4),(8,9,0,5)]
After removing tuple having length 2: [(2,5,7),(3,4)]

Corresct answer is: c). Original list: [(2,5,7),(3,4),(8,9,0,5)]
After removing tuple having length 2: [(2,5,7),(8,9,0,5)]
Explanation: The code iterates over each tuple in `list1`. If a tuple has a length of 2, it is removed from the list. In the original list, the second tuple `(3,4)` has a length of 2, so it is removed). The resulting list after removing the tuple is `[(2,5,7),(8,9,0,5)]`.

16). What is the output of the following code?

l = [(None,),(5, 4),(1,6,7),(None,1)]
print(“Original list: “, l)
for tup in l:
    for ele in tup:
        if ele == None:
            l.remove(tup)
print(“After removing tuples: “, l)

a). Original list: [(None,),(5, 4),(1,6,7),(None,1)]
After removing tuples: [(5, 4),(1,6,7),(None,1)]
b). Original list: [(None,),(5, 4),(1,6,7),(None,1)]
After removing tuples: [(5, 4),(1,6,7)]
c). Original list: [(None,),(5, 4),(1,6,7),(None,1)]
After removing tuples: [(5, 4),(1,6,7),(None,)]
d). Original list: [(None,),(5, 4),(1,6,7),(None,1)]
After removing tuples: [(5, 4),(1,6,7),(None,1)]

Corresct answer is: b). Original list: [(None,),(5, 4),(1,6,7),(None,1)]
After removing tuples: [(5, 4),(1,6,7)]
Explanation: The code iterates over the list l and checks each element of the tuples. If an element is equal to None, the corresponding tuple is removed from the list.

17). What is the output of the following code?

l = [(1, 5), (7, 8), (4, 0), (3, 6)]
print(“Original list of tuples: “, l)
res = sorted(l, key=lambda tup: tup[0])
print(“After sorting list of tuples by first element: “, res)

a). Original list of tuples: [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by first element: [(1, 5), (3, 6), (4, 0), (7, 8)]
b). Original list of tuples: [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by first element: [(4, 0), (3, 6), (1, 5), (7, 8)]
c). Original list of tuples: [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by first element: [(1, 5), (7, 8), (3, 6), (4, 0)]
d). Original list of tuples: [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by first element: [(7, 8), (4, 0), (3, 6), (1, 5)]

Corresct answer is: a). Original list of tuples: [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by first element: [(1, 5), (3, 6), (4, 0), (7, 8)]
Explanation: The code sorts the list of tuples l based on the first element of each tuple using the sorted() function and a lambda function as the key. The output will be [(4, 0), (3, 6), (1, 5), (7, 8)], where the tuples are sorted in ascending order based on the first element.

18). What is the output of the following code?

l = [(1, 5), (7, 8), (4, 0), (3, 6)]
print(“Original list of tuples: “, l)
res = sorted(l, key=lambda tup: tup[1])
print(“After sorting list of tuples by second element: “, res)

a). Original list of tuples: [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by second element: [(4, 0), (1, 5), (3, 6), (7, 8)]
b). Original list of tuples: [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by second element: [(4, 0), (7, 8), (1, 5), (3, 6)]
c). Original list of tuples: [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by second element: [(4, 0), (3, 6), (1, 5), (7, 8)]
d). Original list of tuples: [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by second element: [(1, 5), (3, 6), (4, 0), (7, 8)]

Corresct answer is: a). Original list of tuples: [(1, 5), (7, 8), (4, 0), (3, 6)]
After sorting list of tuples by second element: [(4, 0), (1, 5), (3, 6), (7, 8)]
Explanation: The original list of tuples l is [(1, 5), (7, 8), (4, 0), (3, 6)]. The sorted() function is used to sort the list of tuples based on the second element of each tuple. The key=lambda tup: tup[1] specifies that the second element of each tuple should be used for sorting.

19). What is the output of the following code?

l = [(4, 5, 6), (6,), (2, 3), (6, 7, 8, 9, 0)]
print(“Original list of tuples: “, l)
res = sorted(l, key=lambda tup: len(tup))
print(“After sorting list of tuples by length of tuples: “, res)

a). Original list of tuples: [(4, 5, 6), (6,), (2, 3), (6, 7, 8, 9, 0)]
After sorting list of tuples by length of tuples: [(6,), (2, 3), (4, 5, 6), (6, 7, 8, 9, 0)]
b). Original list of tuples: [(4, 5, 6), (6,), (2, 3), (6, 7, 8, 9, 0)]
After sorting list of tuples by length of tuples: [(6, 7, 8, 9, 0), (4, 5, 6), (2, 3), (6,)]
c). Original list of tuples: [(4, 5, 6), (6,), (2, 3), (6, 7, 8, 9, 0)]
After sorting list of tuples by length of tuples: [(6,), (2, 3), (6, 7, 8, 9, 0), (4, 5, 6)]
d). Original list of tuples: [(4, 5, 6), (6,), (2, 3), (6, 7, 8, 9, 0)]
After sorting list of tuples by length of tuples: [(2, 3), (4, 5, 6), (6, 7, 8, 9, 0), (6,)]

Corresct answer is: a). Original list of tuples: [(4, 5, 6), (6,), (2, 3), (6, 7, 8, 9, 0)]
After sorting list of tuples by length of tuples: [(6,), (2, 3), (4, 5, 6), (6, 7, 8, 9, 0)]
Explanation: The code sorts the list of tuples `l` based on the length of each tuple using the `sorted()` function and a lambda function as the `key` parameter. The resulting sorted list of tuples will be `[(6,), (2, 3), (4, 5, 6), (6, 7, 8, 9, 0)]`.

20). What is the output of the following code?

tup = (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
print(“Original tuple: “, tup)
d = {}
for char in tup:
    if char not in d:
        d[char] = 0
    if char in d:
        d[char] += 1
print(“Frequency count: “, d)

a). Original tuple: (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
Frequency count: {‘a’: 2, ‘b’: 3, ‘c’: 1, ‘d’: 1}
b). Original tuple: (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
Frequency count: {‘a’: 2, ‘b’: 2, ‘c’: 1, ‘d’: 1}
c). Original tuple: (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
Frequency count: {‘a’: 3, ‘b’: 3, ‘c’: 1, ‘d’: 1}
d). Original tuple: (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
Frequency count: {‘a’: 1, ‘b’: 2, ‘c’: 1, ‘d’: 1}

Corresct answer is: a). Original tuple: (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
Frequency count: {‘a’: 2, ‘b’: 3, ‘c’: 1, ‘d’: 1}
Explanation: The code iterates over each character in the tuple tup and updates the dictionary d with the frequency count of each character.

21). What is the output of the following code?

l = [(1,4),(4,5,6),(2,),(7,6,8,9),(3,5,6,0,1)]
l1 = []
print(“Original list of tuples: “, l)
for tup in l:
    if len(tup)>3:
        l1.append(tup)
print(“After removing tuples: “, l1)

a). Original list of tuples: [(1,4),(4,5,6),(2,),(7,6,8,9),(3,5,6,0,1)]
After removing tuples: [(4,5,6),(7,6,8,9),(3,5,6,0,1)]
b). Original list of tuples: [(1,4),(4,5,6),(2,),(7,6,8,9),(3,5,6,0,1)]
After removing tuples: [(1,4),(2,)]
c). Original list of tuples: [(1,4),(4,5,6),(2,),(7,6,8,9),(3,5,6,0,1)]
After removing tuples: [(7,6,8,9),(3,5,6,0,1)]
d). Original list of tuples: [(1,4),(4,5,6),(2,),(7,6,8,9),(3,5,6,0,1)]
After removing tuples: []

Corresct answer is: c). Original list of tuples: [(1,4),(4,5,6),(2,),(7,6,8,9),(3,5,6,0,1)]
After removing tuples: [(7,6,8,9),(3,5,6,0,1)]
Explanation: The code iterates over each tuple in the list l and checks if the length of the tuple is greater than 3. If it is, the tuple is appended to the list l1. The original list of tuples is [(1,4),(4,5,6),(2,),(7,6,8,9),(3,5,6,0,1)], and after removing tuples with length greater than 3, the updated list is [(4,5,6),(7,6,8,9),(3,5,6,0,1)].

22). What is the output of the following code?

l = [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
print(“Original list of tuples: “,l)
d = {}
for tup in l:
    if tup not in d:
        d[tup] = 0
    if tup in d:
        d[tup] += 1
print(“Frequency count : “,d)

a). Original list of tuples: [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
Frequency count: {(‘s’,’q’): 2, (‘t’,’o’,’o’,’l’): 1, (‘p’,’y’): 1}
b). Original list of tuples: [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
Frequency count: {(‘s’,’q’): 1, (‘t’,’o’,’o’,’l’): 1, (‘p’,’y’): 1}
c). Original list of tuples: [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
Frequency count: {(‘s’,’q’): 1, (‘t’,’o’,’o’,’l’): 2, (‘p’,’y’): 1}
d). Original list of tuples: [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
Frequency count: {(‘s’,’q’): 2, (‘t’,’o’,’o’,’l’): 2, (‘p’,’y’): 1}

Corresct answer is: a). Original list of tuples: [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
Frequency count: {(‘s’,’q’): 2, (‘t’,’o’,’o’,’l’): 1, (‘p’,’y’): 1}
Explanation: The code initializes an empty dictionary d). It then iterates over each tuple tup in the list l. If the tuple tup is not already in the dictionary d, it adds it with a value of 0. Then, it increments the value of tup in d by 1. The final d dictionary contains the frequency count of each tuple in the list.

23). What is the output of the following code?

tup = (1, 2, 3, 4)
if len(set(tup)) == len(tup):
    print(“Tuple is distinct”)
else:
    print(“Tuple is not distinct”)

a). Tuple is distinct
b). Tuple is not distinct
c). Error: invalid syntax
d). Error: unsupported operand type(s)

Corresct answer is: a). Tuple is distinct
Explanation: The code snippet checks whether the given tuple tup is distinct or not. It does so by converting the tuple to a set using the set() function, which removes any duplicate elements since sets only contain unique elements. The len() function is then used to compare the lengths of the original tuple and the set. If the lengths are equal, it means that all elements in the tuple are distinct. 

24). What is the output of the following code?

tup1 = (3, 4, 5, 4, 6, 3)
if len(set(tup1)) == len(tup1):
    print(“Tuple is distinct”)
else:
    print(“Tuple is not distinct”)

a). “Tuple is distinct”
b). “Tuple is not distinct”
c). Error: invalid syntax
d). Error: undefined variable ‘tup1’

Corresct answer is: b). “Tuple is not distinct”
Explanation: The code checks if the length of the set created from tup1 is equal to the length of tup1. If they are not equal, it means there are duplicate elements in the tuple, and the output will be “Tuple is not distinct.”

25). What is the output of the following code?

tup = (4, 1, 7, 5)
print(“Original tuple: “, tup)
tup1 = str(tup)
print(“After converting to a string: “, tup1)
print(“Type of new tuple: “, type(tup1))

a). Original tuple: (4, 1, 7, 5)
After converting to a string: (4, 1, 7, 5)
Type of new tuple: tuple
b). Original tuple: (4, 1, 7, 5)
After converting to a string: (4, 1, 7, 5)
Type of new tuple: <class ‘str’>
c). Original tuple: [4, 1, 7, 5]
After converting to a string: ‘4, 1, 7, 5’
Type of new tuple: list
d). Original tuple: (4, 1, 7, 5)
After converting to a string: [4, 1, 7, 5]
Type of new tuple: list

Corresct answer is: b). Original tuple: (4, 1, 7, 5)
After converting to a string: (4, 1, 7, 5)
Type of new tuple: <class ‘str’>
Explanation: In the given code, the tuple `tup` is converted to a string using the `str()` function. The resulting string will be (4, 1, 7, 5). The `type()` function is used to determine the type of the variable `tup1`, which will be `str`.

Python Tuple MCQ : Set 2

Python Tuple MCQ

1). Which of the following methods is used to insert an element at a specific index in a tuple?

a) insert()
b) add()
c) append()
d) extend()

Correct answer is: a
Explanation: There is no built-in method to insert an element at a specific index in a tuple because tuples are immutable.

2). Can a tuple be converted into a string using the `str()` function?

a) Yes
b) No

Correct answer is: a
Explanation: The `str()` function can be used to convert a tuple into a string representation.

3). Which method is used to remove a specific element from a tuple?

a) remove()
b) delete()
c) discard()
d) Tuples are immutable and cannot be modified)

Correct answer is: d
Explanation: Tuples are immutable, so elements cannot be removed directly.

4). Which of the following statements about tuples is false?

a) Tuples are enclosed in parentheses.
b) Tuples can be used as keys in dictionaries.
c) Tuples are immutable.
d) Tuples can contain elements of different data types.

Correct answer is: d
Explanation: Tuples can contain elements of different data types, so option (d) is false.

5). Which of the following methods is used to convert a list into a tuple?

a) to_tuple()
b) convert_tuple()
c) tuple()
d) list_to_tuple()

Correct answer is: c
Explanation: The `tuple()` function is used to convert a list into a tuple.

6). Which of the following methods is used to find the index of the last occurrence of a specific element in a tuple?

a) count()
b) find()
c) index()
d) rindex()

Correct answer is: d
Explanation: The `rindex()` method is used to find the index of the last occurrence of a specific element in a tuple.

7). Which of the following statements is true regarding tuple unpacking?

a) Tuple unpacking allows assigning multiple variables from a single tuple.
b) Tuple unpacking can only be done with tuples of the same length.
c) Tuple unpacking is not supported in Python.
d) Tuple unpacking is used to merge two tuples into one.

Correct answer is: a
Explanation: Tuple unpacking allows assigning multiple variables from a single tuple, making option (a) true.

8).  Can a tuple be modified after it is created?

a) Yes
b) No

Correct answer is: b
Explanation: Tuples are immutable, meaning they cannot be modified after creation.

9). Which of the following methods is used to check if all elements in a tuple are of the same value?

a) same()
b) equal()
c) all_equal()
d) None of the above

Correct answer is: a
Explanation: The method same() does not exist in Python. To check if all elements in a tuple are of the same value, we can compare the first element with the rest of the elements using the all() function.

10). Which of the following methods is used to find the minimum value in a tuple?

a) min()
b) minimum()
c) smallest()
d) None of the above

Correct answer is: a
Explanation: The min() function is used to find the minimum value in a tuple. It returns the smallest element based on their natural ordering.

11). Can a tuple be used as a key in a set?

a) Yes
b) No

Correct answer is: b
Explanation: No, a tuple cannot be used as a key in a set. Sets require elements to be hashable, and since tuples are mutable, they are not hashable.

12).  Which method is used to find the maximum value in a tuple?

a) max()
b) maximum()
c) largest()
d) None of the above

Correct answer is: a
Explanation: The max() function is used to find the maximum value in a tuple. It returns the largest element based on their natural ordering.

13). Can a tuple contain mutable objects like lists?

a) Yes
b) No

Correct answer is: a
Explanation: Yes, a tuple can contain mutable objects like lists. However, the tuple itself remains immutable, but the objects it contains can be mutable.

14). Which of the following methods is used to find the length of a tuple?

a) length()
b) count()
c) size()
d) len()

Correct answer is: d
Explanation: The built-in len() function is used to find the length of a tuple. It returns the number of elements in the given tuple.

15). Can a tuple be used as an element in another tuple?

a) Yes
b) No

Correct answer is: a
Explanation: Yes, a tuple can be used as an element in another tuple. Tuples can contain elements of any data type, including other tuples.

16). Which method is used to convert a tuple into a set?

a) set()
b) convert_set()
c) to_set()
d) None of the above

Correct answer is: a
Explanation: The set() function can be used to convert a tuple into a set. It creates a new set containing the unique elements from the tuple.

17). Which of the following statements is true regarding the memory efficiency of tuples compared to lists?

a) Tuples are more memory-efficient than lists.
b) Lists are more memory-efficient than tuples.
c) Tuples and lists have the same memory efficiency.
d) Memory efficiency does not depend on the data structure.

Correct answer is: c
Explanation: Tuples and lists have the same memory efficiency in terms of storing elements. The memory consumption depends on the number and size of the elements, not the data structure itself.

18). Can a tuple be sorted using the `sort()` method?

a) Yes
b) No

Correct answer is: b
Explanation: No, tuples are immutable, and the sort() method is only available for mutable sequences like lists. To sort a tuple, you can convert it to a list, sort the list, and then convert it back to a tuple.

19). What is the output of the following code?

tup = (41, 15, 69, 55)
print(“Maximum value: “, max(tup))

a). Maximum value: 41
b). Maximum value: 69
c). Maximum value: 55
d). Maximum value: 15

Corresct answer is: b) Maximum value: 69
Explanation: The max() function returns the maximum value from the given sequence. In this case, the sequence is the tuple tup containing the values (41, 15, 69, 55). The maximum value in the tuple is 69, so the output will be “Maximum value: 69”.

20). What is the output of the following code?

tup = (36, 5, 79, 25)
print(“Minimum value: “, min(tup))

a). Minimum value: 36
b). Minimum value: 5
c). Minimum value: 79
d). Minimum value: 25

Corresct answer is: b) Minimum value: 5
Explanation: The min() function returns the minimum value from a sequence. In this case, the sequence is the tuple tup containing the values (36, 5, 79, 25). The smallest value in the tuple is 5, so the output will be “Minimum value: 5”.

21). What is the output of the following code?

list1 = [4, 6, 8]
list2 = [7, 1, 4]
tup = tuple(zip(list1, list2))
print(tup)

a). [(4, 7), (6, 1), (8, 4)]
b). [(7, 4), (1, 6), (4, 8)]
c). [(4, 6, 8), (7, 1, 4)]
d). [(4, 7), (6, 1), (8, 4), (0, 0)]

Corresct answer is: a). [(4, 7), (6, 1), (8, 4)]
Explanation: The zip() function takes two or more iterables and aggregates their elements into tuples. In this case, it combines the elements of list1 and list2 into tuples. The output will be [(4, 7), (6, 1), (8, 4)].

22). What is the output of the following code?

list1 = [4, 6, 3, 8]
tup = [(val, pow(val, 3)) for val in list1]
print(tup)

a). `[(4, 64), (6, 216), (3, 27), (8, 512)]`
b). `[(4, 12), (6, 18), (3, 9), (8, 24)]`
c). `[(64, 4), (216, 6), (27, 3), (512, 8)]`
d). `[(12, 4), (18, 6), (9, 3), (24, 8)]`

Corresct answer is: a). `[(4, 64), (6, 216), (3, 27), (8, 512)]`

Explanation: The code snippet demonstrates list comprehension and uses the `pow()` function to calculate the cube of each value in the `list1` list. The resulting list comprehension creates a new list of tuples, where each tuple consists of the original value from `list1` and its cube. The output will be `[(4, 64), (6, 216), (3, 27), (8, 512)]`.

23). What is the output of the following code?

tup = (4, 8, 9, 1)
print(“Number in the tuple with index 2: “, tup[2])

a). Number in the tuple with index 2: 4
b). Number in the tuple with index 2: 8
c). Number in the tuple with index 2: 9
d). Number in the tuple with index 2: 1

Corresct answer is: c). Number in the tuple with index 2: 9
Explanation: The code defines a tuple `tup` with elements (4, 8, 9, 1). The index starts from 0, so `tup[2]` accesses the element at index 2, which is 9. Therefore, the output will be “Number in the tuple with index 2: 9”.

24). What is the output of the following code?

tup = (6, 7, 3)
(a, b, c) = tup
print(“a: “, a)
print(“b: “, b)
print(“c: “, c)

a). a: 6, b: 7, c: 3
b). a: 7, b: 3, c: 6
c). a: 6, b: 3, c: 7
d). a: 7, b: 6, c: 3

Corresct answer is: a). a: 6, b: 7, c: 3
Explanation: In the given code, the tuple tup contains three elements: 6, 7, and 3. The variables a, b, and c are assigned the values of the corresponding elements in the tuple using tuple unpacking. Therefore, a will be 6, b will be 7, and c will be 3.

25). What is the output of the following code?

tup = (18, 65, 3, 45)
print(“Old tuple: “, tup)
tup = list(tup)
tup.append(15)
tup = tuple(tup)
print(“New tuple: “, tup)

a). Old tuple: (18, 65, 3, 45)
New tuple: (18, 65, 3, 45, 15)
b). Old tuple: (18, 65, 3, 45)
New tuple: (18, 65, 3, 45)
c). Old tuple: [18, 65, 3, 45]
New tuple: (18, 65, 3, 45, 15)
d). Old tuple: [18, 65, 3, 45]
New tuple: [18, 65, 3, 45, 15]

Corresct answer is: c). Old tuple: [18, 65, 3, 45]
New tuple: (18, 65, 3, 45, 15)
Explanation: The code first converts the tuple tup to a list using the list() function. Then, the number 15 is appended to the list. Finally, the list is converted back to a tuple using the tuple() function. Therefore, the output will be:
Old tuple: [18, 65, 3, 45]
New tuple: (18, 65, 3, 45, 15)