Python Function MCQ : Set 4

Python Function MCQ

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

def square(d):
    a = {}
    for key,value in d.items():
        a[key] = value**2
    return a
square({‘a’:4,’b’:3,’c’:12,’d’:6})

a) {‘a’: 16, ‘b’: 9, ‘c’: 144, ‘d’: 36}
b) {‘a’: 8, ‘b’: 6, ‘c’: 24, ‘d’: 12}
c) {‘a’: 2, ‘b’: 3, ‘c’: 4, ‘d’: 6}
d) {‘a’: 4, ‘b’: 3, ‘c’: 12, ‘d’: 6}

Correct answer is: a) {‘a’: 16, ‘b’: 9, ‘c’: 144, ‘d’: 36}
Explanation: The code defines a function `square` that takes a dictionary `d` as an argument. Inside the function, it initializes an empty dictionary `a`. Then, it iterates over the key-value pairs of the input dictionary using the `items()` method. For each key-value pair, it calculates the square of the value and assigns it as a value in the new dictionary `a`, with the same key as the original dictionary.

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

def prime(lower, upper):
    print(“Prime numbers between”, lower, “and”, upper, “are:”)

    for num in range(lower, upper + 1):
        count = 0
        for i in range(1, num + 1):
            if num % i == 0:
                count += 1
        if count == 2:
            print(i, end=” “)

prime(1, 100)

a) Prime numbers between 1 and 100 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
b) Prime numbers between 1 and 100 are: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
c) Prime numbers between 1 and 100 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
d) Prime numbers between 1 and 100 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Correct answer is: a) Prime numbers between 1 and 100 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Explanation: The function `prime()` takes two parameters, `lower` and `upper`, which represent the range of numbers to check for prime numbers. The function then iterates over each number in the range using a for loop, starting from `lower` and ending at `upper + 1`. Inside the loop, a variable `count` is initialized to 0. Another for loop iterates from 1 to the current number (`num`). Within this inner loop, the program checks if the current number (`num`) is divisible evenly by the current value of `i`. If it is, the `count` is incremented by 1. After the inner loop finishes, the program checks if the `count` is equal to 2. If it is, it means the number is only divisible by 1 and itself, indicating it is a prime number. In this code snippet, the function `prime(1, 100)` is called, which finds and prints all the prime numbers between 1 and 100.

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

def odd(lower, upper):
    print(“Odd numbers between”, lower, “and”, upper, “are:”)

    for num in range(lower, upper + 1):
        if num % 2 != 0:
            print(num, end=” “)

odd(1, 50)

a) Odd numbers between 1 and 50 are: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
b) Odd numbers between 1 and 50 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
c) Odd numbers between 1 and 50 are: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
d) Odd numbers between 1 and 50 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

Correct answer is: a) Odd numbers between 1 and 50 are: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
Explanation: The function `odd` takes in two parameters, `lower` and `upper`, and prints the odd numbers between `lower` and `upper`. In this case, the function is called with `lower` equal to 1 and `upper` equal to 50. The for loop iterates over the range from 1 to 51 (upper + 1). For each number in the range, if the number is not divisible by 2 (i.e., it is an odd number), it is printed with a space at the end. Therefore, the output will be “Odd numbers between 1 and 50 are: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49”.

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

def add(a, b):
    total = a + b
    return total

add(5, 15)

a) 5
b) 15
c) 20
d) None

Correct answer is: c) 20
Explanation: The function `add()` takes two parameters, `a` and `b`, and adds them together. In this case, `a` is 5 and `b` is 15. The function returns the sum of `a` and `b`, which is 20. When the `add(5, 15)` function call is executed, it returns the value 20.

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

def fruit(fname, fprice, quantity):
    print(“Fruit name: “, fname)
    print(“Fruit price: “, price)
    print(“Fruit quantity in kg: “, quantity)
    print(“Bill: “, fprice * quantity)

fruit(“Apple”, 100, 2)

a) Fruit name: Apple, Fruit price: 100, Fruit quantity in kg: 2, Bill: 200
b) Fruit name: Apple, Fruit price: 100, Fruit quantity in kg: 2, Bill: 100
c) Fruit name: Apple, Fruit price: 200, Fruit quantity in kg: 2, Bill: 400
d) Fruit name: Apple, Fruit price: 200, Fruit quantity in kg: 4, Bill: 800

Correct answer is: a) Fruit name: Apple, Fruit price: 100, Fruit quantity in kg: 2, Bill: 200
Explanation: The function `fruit` takes three parameters: `fname` (fruit name), `fprice` (fruit price), and `quantity` (fruit quantity in kg). It then prints the values of these parameters along with the calculated bill, which is the product of `fprice` and `quantity`.

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

def leap(a):
    if (a % 100 != 0 or a % 400 == 0) and a % 4 == 0:
        print(“The given year is leap year.”)
    else:
        print(“The given year is not leap year.”)

leap(2005)

a) The given year is leap year.
b) The given year is not leap year.
c) The code raises an error.
d) None of the above.

Correct answer is: b) The given year is not a leap year.
Explanation: In the code, the function `leap()` takes a year as input and checks if it is a leap year or not. The condition `(a % 100 != 0 or a % 400 == 0) and a % 4 == 0` is used to determine the leap year. For the given input of `2005`, the condition `(a % 100 != 0 or a % 400 == 0) and a % 4 == 0` evaluates to `(True or False) and False`, which simplifies to `True and False`. Since the logical AND operator requires both conditions to be True for the entire expression to be True, the code execution enters the `else` block and prints “The given year is not a leap year.”

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

def reverse():
    num = n = 123
    rev = 0
    while n > 0:
        r = n % 10
        rev = (rev * 10) + r
        n = n // 10
    print(“Reverse number: “, rev)

reverse()

a) Reverse number: 123
b) Reverse number: 321
c) Reverse number: 312
d) Reverse number: 132

Correct answer is: b) Reverse number: 321
Explanation: The code defines a function `reverse()` that calculates the reverse of a given number. In this case, the initial value of `num` and `n` is 123. Inside the `while` loop, the remainder of `n` divided by 10 (`r`) is calculated. It is then added to the `rev` variable after multiplying it by 10 (shifting the existing digits to the left) to make space for the new digit. The updated `rev` becomes the new reversed number. The variable `n` is then divided by 10 to remove the rightmost digit. This process continues until `n` becomes 0, at which point the loop terminates. Finally, the reversed number is printed using the `print()` function, resulting in “Reverse number: 321” as the output.

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

def library(bname, came):
    print(“Book name: “, bname)
    print(“Borrowed by:”, cname)

library(“Harry Potter”, “Yash”)

a) Book name: Harry Potter
b) Harry Potter Yash
c) Book name: Harry potter Borrowed by: Yash
d) Book name: Harry Potter Borrowed by: Yash

Correct answer is: d) Book name: Harry Potter Borrowed by: Yash
Explanation: The function `library` takes two parameters `bname` and `cname`. When the function is called with the arguments “Harry Potter” and “Yash”, it prints “Book name: Harry Potter” and “Borrowed by: Yash” using the `print` function. Therefore, the output will be “Book name: Harry Potter Borrowed by: Yash”.

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

def binary(n1, n2):
    result = bin(int(n1, 2) + int(n2, 2))
    print(f”Addition of binary numbers {n1}, {n2}: “, result[2:]) binary(‘100010’, ‘101001’)

a) 1001011
b) 1000111
c) 10101011
d) 111011

Correct answer is: a) 1001011
Explanation: The given code defines a function binary(n1, n2) that takes two binary numbers represented as strings n1 and n2. It then performs binary addition on these two numbers.

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

def search():
    str1 = “python programming”
    str2 = “python”
    count = 0
    for word in str1.split(” “):
        if word == str2:
            count += 1
    if count > 0:
        print(f”{str2} is in {str1}”)
    else:
        print(f”{str2} is not in {str1}”)

search()

a) python is in python programming
b) python programming is in python
c) python is not in python programming
d) python programming is not in python

Correct answer is: a) python is in python programming
Explanation: The code defines a function named `search()`. Inside the function, the variable `str1` is assigned the value “python programming” and `str2` is assigned the value “python”. The variable `count` is initialized to 0. The code then splits `str1` into a list of words using the space character as the separator. It iterates over each word in the list and checks if it is equal to `str2`. If a match is found, `count` is incremented by 1. After the loop, the code checks if `count` is greater than 0. If it is, it means that `str2` was found in `str1`, and it prints “{str2} is in {str1}”. Otherwise, it prints “{str2} is not in {str1}”.

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

def length():
    str1 = “sqatools in best for learning python”
    l = str1.split(” “)
    print(f”Length of the last word {l[-1]} in the string: “, len(l[-1]))

length()

a) Length of the last word “python” in the string: 6
b) Length of the last word “sqatools” in the string: 8
c) Length of the last word “learning” in the string: 8
d) Length of the last word “in” in the string: 2

Correct answer is: a) Length of the last word “python” in the string: 6
Explanation: The code defines a function `length()` that splits the string `str1` into a list of words using the space as the delimiter. The last word of the string, accessed using `l[-1]`, is “python”. The `len()` function is then used to calculate the length of this last word, which is 6 characters. Finally, the function prints the message “Length of the last word python in the string: ” followed by the length of the word. Thus, the output of the code is “Length of the last word python in the string: 6”.

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

def mobile_number():
    num = 24568526
    if len(str(num)) == 10:
        print(“It is a valid phone number”)
    else:
        print(“It is not a valid phone number”)

mobile_number()

a) It is a valid phone number
b) It is not a valid phone number
c) Error: Invalid input format
d) None of the above

Correct answer is: b) It is not a valid phone number
Explanation: The code defines a function `mobile_number()` that assigns the value `24568526` to the variable `num`. The code then checks if the length of the string representation of `num` is equal to 10. In this case, the length of the string `”24568526″` is 8, which is not equal to 10. Therefore, the code prints “It is not a valid phone number”.

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

def to_number():
    num = 2563
    str1 = “”

    for i in str(num):
        if i == “1”:
            str1 += “One”
        elif i == “2”:
            str1 += “Two”
        elif i == “3”:
            str1 += “Three”
        elif i == “4”:
            str1 += “Four”
        elif i == “5”:
            str1 += “Five”
        elif i == “6”:
            str1 += “Six”
        elif i == “7”:
            str1 += “Seven”
        elif i == “8”:
            str1 += “Eight”
        elif i == “9”:
            str1 += “Nine”

    print(str1)

to_number()

a) “TwoFiveSixThree”
b) “TwoFiveSixThree”
c) “Two Five Six Three”
d) “2563”

Correct answer is: c) “Two Five Six Three”
Explanation: The function `to_number` converts the number 2563 into its string representation with words. It iterates over each digit in the string representation of the number using a for loop. Inside the loop, it checks each digit and appends the corresponding word to the variable `str1`.

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

import itertools
def permutations():
    string = “ABC”
    list1 = list(string)
    permutations = list(itertools.permutations(list1))
    return permutations

permutations()

a) [(‘A’, ‘B’, ‘C’), (‘A’, ‘C’, ‘B’), (‘B’, ‘A’, ‘C’), (‘B’, ‘C’, ‘A’), (‘C’, ‘A’, ‘B’), (‘C’, ‘B’, ‘A’)]
b) [‘ABC’, ‘ACB’, ‘BAC’, ‘BCA’, ‘CAB’, ‘CBA’]
c) [(‘A’, ‘A’, ‘A’), (‘B’, ‘B’, ‘B’), (‘C’, ‘C’, ‘C’)]
d) [‘A’, ‘B’, ‘C’]

Correct answer is: a) [(‘A’, ‘B’, ‘C’), (‘A’, ‘C’, ‘B’), (‘B’, ‘A’, ‘C’), (‘B’, ‘C’, ‘A’), (‘C’, ‘A’, ‘B’), (‘C’, ‘B’, ‘A’)]
Explanation: The code uses the `itertools.permutations()` function to generate all possible permutations of the characters in the string “ABC”. The function returns a list of tuples, where each tuple represents a different permutation. In this case, the output will be `[(‘A’, ‘B’, ‘C’), (‘A’, ‘C’, ‘B’), (‘B’, ‘A’, ‘C’), (‘B’, ‘C’, ‘A’), (‘C’, ‘A’, ‘B’), (‘C’, ‘B’, ‘A’)]`, representing all the possible permutations of the characters ‘A’, ‘B’, and ‘C’.

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

def login():
    name = “Ketan”
    password = “password1234”
    print(“Credential accepted”)

login()

a) Credential accepted
b) Ketan
c) password1234
d) None

Correct answer is: a) Credential accepted
Explanation: When the function `login()` is called, it assigns the string “Ketan” to the variable `name` and the string “password1234” to the variable `password`. The `print()` function is then used to output the message “Credential accepted” to the console. Therefore, the output of the code snippet will be “Credential accepted”.

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

def fun(string):
    a = {}
    l = string.split(” “)
    for word in l:
        a[word[0] + word[-1]] = word
    return a

result = fun(“Python is easy li Learn”)
print(result)

a) {‘Pi’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘Li’: ‘Learn’}
b) {‘Pn’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘li’: ‘li’, ‘Ln’: ‘Learn’}
c) {‘Ph’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘Le’: ‘Learn’}
d) {‘Py’: ‘Python’, ‘is’: ‘is’, ‘ea’: ‘easy’, ‘Le’: ‘Learn’}

Correct answer is: b) {‘Pn’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘li’: ‘li’, ‘Ln’: ‘Learn’}
Explanation: The function fun takes a string as input and splits it into a list of words using the space as a delimiter. It then iterates over each word in the list. For each word, it creates a dictionary entry where the key is the concatenation of the first character and the last character of the word, and the value is the word itself. Finally, it returns the resulting dictionary.

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

def hcf(num1,num2):
    if num1 > num2:
        smaller = num2
    else:
        smaller = num1

    for i in range(1, smaller+1):
        if((num1 % i == 0) and (num2 % i == 0)):
            hcf = i

    print(f”H.C.F of {num1} and {num2}: {hcf}”)

num1 = 24
num2 = 54
hcf(num1,num2)

a) H.C.F of 24 and 54: 6
b) H.C.F of 24 and 54: 12
c) H.C.F of 24 and 54: 24
d) H.C.F of 24 and 54: 54

Correct answer is: a) H.C.F of 24 and 54: 6
Explanation: The given code calculates the highest common factor (H.C.F) of `num1` and `num2` using the Euclidean algorithm. In this case, `num1` is 24 and `num2` is 54. The code starts by assigning the smaller value (`num1` or `num2`) to the variable `smaller`. Then, it iterates from 1 to `smaller` using a for loop. For each iteration, it checks if both `num1` and `num2` are divisible by the current number `i`. If they are, the current number `i` is assigned to the variable `hcf`. Finally, it prints the calculated H.C.F using the f-string format. In this scenario, the H.C.F of 24 and 54 is 6. Therefore, the output of the code will be “H.C.F of 24 and 54: 6”.

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

def average(numbers):
    total = sum(numbers)
    average = total / len(numbers)
    return average

scores = [90, 85, 92, 88, 95]
result = average(scores)
print(result)

a) 88
b) 90
c) 92
d) 95

Correct answer is: a) 88
Explanation: The code defines a function find_average that calculates the average of a list of numbers. It calculates the sum of the numbers using the sum() function and divides it by the length of the list. In this case, the average of the scores list [90, 85, 92, 88, 95] is 88. Therefore, the output will be 88.

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

def product(a, b=2):
    return a * b

result1 = product(5)
result2 = product(5, 3)
print(result1, result2)

a) 10 15
b) 5 15
c) 10 6
d) 5 6

Correct answer is: a) 10 15
Explanation: The function calculate_product takes two parameters, a and b, with a default value of 2 for b. If the b argument is not provided, it uses the default value. In this case, result1 is calculated as 5 * 2, which is 10, and result2 is calculated as 5 * 3, which is 15. Therefore, the output will be “10 15”.

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

def power(base, exponent):
    return base ** exponent

result = power(2, 3)
print(result)

a) 6
b) 8
c) 16
d) 23

Correct answer is: c) 16
Explanation: The function calculate_power calculates the result of raising the base to the exponent using the exponentiation operator **. In this case, 2 raised to the power of 3 is 8. Therefore, the output will be 8.

Python Function MCQ : Set 3

Python Function MCQ

1). What is the purpose of the given Python function?

def add(a,b):
    total = a+b
    print(“Total: “,total)

num1 = int(input(“Enter number 1: “))
num2 = int(input(“Enter number 2: “))

add(num1,num2)

a) It multiplies two numbers and prints the result.
b) It divides two numbers and prints the result.
c) It subtracts two numbers and prints the result.
d) It adds two numbers and prints the result.

Correct answer is: d) It adds two numbers and prints the result.
Explanation: The function add(a, b) takes two parameters a and b, adds them together, and stores the result in the variable total. Then it prints the result using the print statement. In the provided code, num1 is set to 10 and num2 is set to 20. When add(num1, num2) is called, it adds 10 and 20, resulting in a total of 30, which is printed as “Total: 30”.

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

def String(str1):
    print(str1*10)

string = “Python”
String(string)

a) PythonPythonPythonPythonPythonPythonPythonPythonPythonPython
b) 10Python
c) 10
d) Python10

Correct answer is: a) PythonPythonPythonPythonPythonPythonPythonPythonPythonPython
Explanation: The given code defines a function called `String(str1)` that takes a string as input and prints it ten times. It then creates a variable `string` with the value “Python” and calls the `String()` function, passing the `string` variable as an argument. When the function is called with `String(string)`, the function takes the input string “Python” and multiplies it by 10.

3). What is the purpose of the following code snippet?

def table(num):
    a = 0
    for i in range(1, 11):
        a = i * num
    print(i, “*”, num, “=”, a)

n = 5
table(n)

a) It calculates the factorial of a given number.
b) It generates a multiplication table for a given number.
c) It prints the squares of numbers from 1 to 10.
d) It calculates the sum of a given number and its multiples.

Correct answer is: b) It generates a multiplication table for a given number.
Explanation: The code defines a function named `table` that takes a parameter `num`. Within the function, a for loop iterates over the range from 1 to 11 (exclusive). In each iteration, the variable `a` is assigned the result of multiplying `i` by `num`. Then, it prints the equation `i * num = a`. The variable `n` is set to 5, and the `table` function is called with `n` as the argument, generating a multiplication table for 5.

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

def largest(a,b,c):
    if a>b:
        if a>c:
            print(f”{a} is the greatest number”)
    elif b>a:
        if b>c:
             print(f”{b} is the greatest number”)
    else:
        print(f”{c} is the greatest number”)

num1 = 50
num2 = 60
num3 = 44

largest(num1,num2,num3)

a) 50 is the greatest number
b) 60 is the greatest number
c) 44 is the greatest number
d) No output is printed

Correct answer is: b) 60 is the greatest number
Explanation: The function largest is called with three numbers: 50, 60, and 44. Among these numbers, 60 is the greatest. Therefore, the output of the function call is “60 is the greatest number”, which will be printed to the console.

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

def total(list1):
    t = 0
    for val in list1:
        t += val
    print(“Sum of given list: “, t)

l = [6, 9, 4, 5, 3]
total(l)

a) Sum of given list: 27
b) Sum of given list: 27 [6, 9, 4, 5, 3]
c) 27
d) None

Correct answer is: a) Sum of given list: 27
Explanation: The function `total` takes a list as input and iterates through each element, adding them to the variable `t`. In this case, the list `l` contains the elements [6, 9, 4, 5, 3], and their sum is 27. The function prints “Sum of given list: 27” as the output. The print statement is inside the function, and it displays the sum directly to the console.

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

def mul(list1):
    t = 1
    for val in list1:
        t *= val
    print(“Product of elements in the given list: “,t)

l = [-8, 6, 1, 9, 2]
mul(l)

a) 0
b) 1
c) 864
d) -864

Correct answer is: d) -864
Explanation: The function “mul(l)” is called with the list “[-8, 6, 1, 9, 2]”. The function calculates the product of all elements in the list: (-8) * 6 * 1 * 9 * 2 = -864. The product (-864) is then printed as the output.

7). What is the purpose of the following code snippet?

def rev(str1):
    a = str1[::-1]
    print(“Reverse of the given string: “, a)

string = “Python1234”
rev(string)

a) It reverses the order of characters in a given string.
b) It checks if the given string is a palindrome.
c) It prints the given string without any modifications.
d) It generates an error due to an undefined function.

Correct answer is: a) It reverses the order of characters in a given string.
Explanation: The function `rev` takes a string `str1` as input and assigns the reverse of the string to the variable `a` using slicing with a step of -1. The `[::-1]` notation is used to reverse the order of characters in the string. Finally, the function prints the reversed string as “Reverse of the given string: ” followed by the value of `a`. In the given code, the string “Python1234” is passed as an argument to the function `rev`, so the output will be “Reverse of the given string: 4321nohtyP”.

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

def check(num):
    if num in range(2, 20):
        print(“True”)
    else:
        print(“False”)
num1 = 15
check(num1)

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

Correct answer is: a) True
Explanation: The given code defines a function `check(num)` that takes a parameter `num`. Inside the function, it checks if the value of `num` is in the range from 2 (inclusive) to 20 (exclusive) using the `in` keyword with the `range()` function. If `num` is within this range, it prints “True”, otherwise, it prints “False”.

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

def unique(list1):
    print(list(set(list1)))

l = [2, 2, 3, 1, 4, 4, 4, 4, 4, 6]
unique(l)

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

Correct answer is: a) [2, 3, 1, 4, 6]
Explanation: The function `unique` takes a list as an argument and uses the `set()` function to remove duplicate elements from the list. The `set()` function creates an unordered collection of unique elements. When the `set()` is converted back to a list using the `list()` function, the order of elements may differ.

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

def prime(num):
    count = 0

    for i in range(2, num):
        if num % i == 0:
            count += 1

    if count > 0:
        print(“It is not a prime number”)
    else:
        print(“It is a prime number”)

num1 = 7
prime(num1)

a) It is not a prime number
b) It is a prime number
c) Error
d) None

Correct answer is: b) It is a prime number
Explanation: The function `prime` takes an input number `num` and checks if it is a prime number. It iterates over the numbers from 2 to `num-1` (exclusive) and checks if `num` is divisible by any of these numbers. If it is divisible by any number, the count is incremented. If the count is greater than 0, it means the number has divisors other than 1 and itself, and thus, it is not a prime number. Otherwise, if the count remains 0, it means the number has no divisors other than 1 and itself, making it a prime number.

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

def even(list1):
    even_list = []
    for val in list1:
        if val % 2 == 0:
    even_list.append(val)
    print(even_list)

l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even(l)

a) [1, 2, 3, 4, 5, 6, 7, 8, 9]
b) [2, 4, 6, 8]
c) [1, 3, 5, 7, 9]
d) [1, 2, 3, 4, 5, 6, 7, 8]

Correct answer is: b) [2, 4, 6, 8]
Explanation: The function `even()` takes a list as input and creates an empty list called `even_list`. It then iterates through each value in the input list. If the value is divisible by 2 (i.e., it is even), it appends it to `even_list`. Finally, it prints `even_list`. In this case, the input list `l` contains numbers from 1 to 9. The even numbers in this list are 2, 4, 6, and 8. Therefore, the output is `[2, 4, 6, 8]`.

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

def square():
    for i in range(1, 11):
        print(i, “:”, i ** 2)

square()

a) 1 : 1, 2 : 4, 3 : 9, 4 : 16, 5 : 25, 6 : 36, 7 : 49, 8 : 64, 9 : 81, 10 : 100
b) 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
c) 1 : 1, 4 : 16, 9 : 81
d) None of the above

Correct answer is: a) 1 : 1, 2 : 4, 3 : 9, 4 : 16, 5 : 25, 6 : 36, 7 : 49, 8 : 64, 9 : 81, 10 : 100
Explanation: The function `square()` uses a for loop to iterate over the numbers from 1 to 10 (inclusive) using the `range(1, 11)` expression. Inside the loop, it prints the current number (`i`) followed by a colon (`:`) and the square of `i` (`i ** 2`).

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

mycode = ‘print(“Python”)’
code = “””
def multiply(x, y):
    return x * y

print(‘sqatools’)
“””
exec(mycode)
exec(code)

a) Python
b) sqatools
c) Python\nsqatools
d) sqatools\nPython

Correct answer is: c) Python\nsqatools
Explanation: The `exec()` function in Python is used to execute dynamically generated Python code. In this code, `mycode` variable contains the string `’print(“Python”)’`, which is executed using `exec(mycode)`. This will print the string “Python” to the console. The `code` variable contains a multi-line string that defines a function called `multiply(x, y)` and prints the string “sqatools” to the console. When `exec(code)` is executed, it will execute the code within the string.

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

def lcm(num1, num2):
    if num1 > num2:
        greater = num1
    else:
        greater = num2

    while True:
        if (greater % num1 == 0) and (greater % num2 == 0):
            lcm = greater
            break
        greater += 1

    print(f”L.C.M of {num1} and {num2}: {lcm}”)

num1 = 12
num2 = 20
lcm(num1, num2)

a) L.C.M of 12 and 20: 60
b) L.C.M of 12 and 20: 12
c) L.C.M of 12 and 20: 20
d) L.C.M of 12 and 20: 240

Correct answer is: a) L.C.M of 12 and 20: 60
Explanation: The function `lcm()` calculates the least common multiple (LCM) of two numbers, `num1` and `num2`. In this case, `num1` is 12 and `num2` is 20. The code first compares the values of `num1` and `num2` and assigns the larger value to the variable `greater`. Next, a `while` loop is initiated. It continues until the condition `True` is met. Within the loop, it checks if the `greater` number is divisible by both `num1` and `num2` using the modulo operator `%`. If it is, it means that `greater` is the LCM, and the value is stored in the variable `lcm`. The loop is then terminated using the `break` statement. Finally, the function prints the result using an f-string, displaying the LCM of `num1` and `num2`.

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

def total():
    t = 0
    for i in range(1, 11):
        t += i
    print(“Total: “, t)

total()

a) Total: 55
b) Total: 45
c) Total: 10
d) Total: 15

Correct answer is: a) Total: 55
Explanation: The code defines a function named `total()`. Inside the function, a variable `t` is initialized to 0. Then, a loop is executed using the `range()` function from 1 to 10 (excluding 11). In each iteration, the loop variable `i` is added to `t`. After the loop finishes, the total value of `t` is printed with the message “Total: “. The loop iterates over the numbers 1 to 10, and each number is added to the total `t`. Therefore, the final value of `t` is the sum of all numbers from 1 to 10, which is 55. Thus, the output of the code is “Total: 55”.

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

def func(*args):
    for num in args:
        print(num**3, end=” “)

func(5, 6, 8, 7)

a) 125 216 512 343
b) 5 6 8 7
c) 15 18 24 21
d) 125 216 512 343 5 6 8 7

Correct answer is: a) 125 216 512 343
Explanation: The function `func` accepts a variable number of arguments using the `*args` syntax, which allows it to receive multiple arguments as a tuple. Inside the function, a loop iterates over each element in `args` and prints the cube of each number.

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

def fact(n):
    fact = 1
    while n > 0:
        fact *= n
        n -= 1
    print(f”Factorial of {num}: {fact}”)

num = 5
fact(num)

a) Factorial of 5: 5
b) Factorial of 5: 120
c) Factorial of 5: 25
d) Factorial of 5: 1

Correct answer is: b) Factorial of 5: 120
Explanation: The code defines a function `fact(n)` to calculate the factorial of a given number. It initializes the variable `fact` to 1 and enters a while loop that iterates while `n` is greater than 0. In each iteration, it multiplies `fact` by `n` and decreases `n` by 1.

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

def fibo():
    num1 = 0
    num2 = 1
    count = 0

    while count < 10:
        print(num1, end=” “)
        n2 = num1 + num2
        num1 = num2
        num2 = n2
        count += 1

fibo()

a) 0 1 1 2 3 5 8 13 21 34
b) 1 1 2 3 5 8 13 21 34 55
c) 0 1 2 3 4 5 6 7 8 9
d) 0 1 1 3 5 8 13 21 34 55

Correct answer is: a) 0 1 1 2 3 5 8 13 21 34
Explanation: The code defines a function `fibo()` that prints the Fibonacci sequence up to the 10th term. The initial values `num1` and `num2` are set to 0 and 1, respectively. The `count` variable keeps track of the number of terms printed. Inside the while loop, `num1` is printed, and then `num1` is updated to the value of `num2`, and `num2` is updated to the sum of the previous `num1` and `num2`. This process continues until the count reaches 10.

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

def unique(l):
    distinct = set(l)
    print(list(distinct))

unique([4, 6, 1, 7, 6, 1, 5])

a) [4, 6, 1, 7, 6, 1, 5]
b) [4, 6, 1, 7, 5]
c) [4, 6, 1, 7]
d) [4, 6, 1, 7, 5, 6, 1]

Correct answer is: b) [4, 6, 1, 7, 5]
Explanation: The function `unique` takes a list `l` as input. It creates a set `distinct` from the elements of the list, which removes duplicate values. Then, the set is converted back to a list using the `list()` function. The `print()` statement displays the resulting list.

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

def dupli(string):
    list1 = []
    for char in string:
        if string.count(char) > 1:
            list1.append(char)
    print(set(list1))

dupli(‘Programming’)

a) {‘r’, ‘g’}
b) {‘o’, ‘m’}
c) {‘r’, ‘m’, ‘g’}
d) {‘r’, ‘o’, ‘m’, ‘g’}

Correct answer is: c) {‘r’, ‘m’, ‘g’}
Explanation: The function `dupli` takes a string as input and checks each character in the string. If the count of the character in the string is greater than 1, it is considered a duplicate and added to the `list1` list. In this case, the string is ‘Programming’, and the characters ‘r’, ‘o’, and ‘g’ occur more than once. The `list1` list will contain these duplicate characters. Finally, the `set()` function is used to convert the `list1` list into a set, which removes duplicate elements. The set containing the duplicate characters is then printed, resulting in {‘r’, ‘m’, ‘g’}.

Python Function MCQ : Set 2

Python Function MCQ

1). What is the purpose of the “return” statement in Python?

a) It defines a loop.
b) It handles exceptions.
c) It terminates the execution of a loop.
d) It specifies the value to be returned by a function.

Correct answer is: d) It specifies the value to be returned by a function.
Explanation: The “return” statement is used to specify the value that a function should return when it is called.

2). Which of the following is a valid way to define a default argument in a function?

a) def my_func(x = 0):
b) def my_func(x, default=0):
c) def my_func(default=0, x):
d) def my_func(x = 0, default):

Correct answer is: a) def my_func(x = 0):
Explanation: Option a) is a valid way to define a default argument in a function. The default value is specified after the “=” sign.

3). What is the purpose of the “reduce()” function in Python?

a) It applies a function to every item in an iterable.
b) It removes duplicates from an iterable.
c) It filters out elements from an iterable based on a condition.
d) It performs a cumulative computation on an iterable.

Correct answer is: d) It performs a cumulative computation on an iterable.
Explanation: The “reduce()” function is used to perform a cumulative computation on an iterable by applying a specified function to the elements.

4). What is the function header?

a) The name of the function and the list of parameters that the function takes.
b) The list of parameters that the function takes.
c) The body of the function.
d) The return value of the function.

Correct answer is: a) The name of the function and the list of parameters that the function takes.

5). What is the body of a function?

a) The code that is executed when the function is called.
b) The list of parameters that the function takes.
c) The return value of the function.
d) The name of the function.

Correct answer is: a) The code that is executed when the function is called.

6). What is a parameter?

a) A variable that is defined inside a function.
b) A variable that is used to store the return value of a function.
c) A variable that is passed to a function.
d) A variable that is used to control the flow of execution of a function.

Correct answer is: c) A variable that is passed to a function.

7). What is the difference between a global variable and local variable?

a) A local variable is defined inside a function, while a global variable is defined outside of a function.
b) A local variable can only be accessed inside the function that defines it, while a global variable can be accessed anywhere in the program.
c) A local variable is created when the function is called, and it is destroyed when the function returns. A global variable is created when the program starts, and it exists until the program ends.
d) All of the above.

Correct answer is: d) All of the above.

8). What is the difference between a built-in function and a user-defined function?

a) A built-in function is a function that is provided by the Python language, while a user-defined function is a function that is defined by the user.
b) A built-in function cannot be modified, while a user-defined function can be modified.
c) A built-in function can only be called from within a function, while a user-defined function can be called from anywhere in the program.
d) All of the above.

Correct answer is: d) All of the above.

9). What is the advantage of using functions?

a) Functions make code more readable and maintainable.
b) Functions can be reused in different parts of the program.
c) Functions can help to improve performance.
d) All of the above.

Correct answer is: d) All of the above.

10). What is the disadvantage of using functions?

a) Functions can make code more complex.
b) Functions can make code less efficient.
c) Functions can make code more difficult to debug.
d) None of the above.

Correct answer is: d) None of the above.

11). What is the purpose of the “zip()” function in Python?

a) It combines two or more iterables element-wise.
b) It compresses data into a ZIP file.
c) It returns the size of an iterable.
d) It reverses the order of elements in an iterable.

Correct answer is: a) It combines two or more iterables element-wise.
Explanation: The “zip()” function is used to combine two or more iterables element-wise, creating an iterator of tuples.

12). Which of the following is a valid way to access the documentation string of a function in Python?

a) help(my_function)
b) my_function.__doc__
c) my_function.document
d) All of the above

Correct answer is: d) All of the above
Explanation: All the given options are valid ways to access the documentation string (docstring) of a function in Python.

13). Which of the following is a valid way to define a recursive function in Python?

a) def my_func():
b) def my_func(x):
c) def my_func():
d) def my_func(x = 0):

Correct answer is: b) def my_func(x):
Explanation: Option b) is a valid way to define a recursive function in Python. The function should have at least one parameter to enable recursive calls with different arguments.

14). Which of the following is a valid way to define a lambda function in Python?

a) lambda x: x + 1
b) def lambda(x): return x + 1
c) def my_func(x): return x + 1
d) lambda: return x + 1

Correct answer is: a) lambda x: x + 1
Explanation: Option a) is a valid way to define a lambda function in Python. It takes a parameter `x` and returns `x + 1`.

15). What is the purpose of the “filter()” function in Python?

a) It applies a function to every item in an iterable.
b) It removes duplicates from an iterable.
c) It filters out elements from an iterable based on a condition.
d) It counts the number of occurrences of an element in an iterable.

Correct answer is: c) It filters out elements from an iterable based on a condition.
Explanation: The “filter()” function is used to filter out elements from an iterable based on a specified condition.

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

def func(x):
    return x * 3

result = func(“abc”)
print(result)

a) a
b) abc
c) abcabcabc
d) None

Correct answer is: c) abcabcabc
Explanation: The function func multiplies the input string x by 3. In this case, “abc” multiplied by 3 results in “abcabcabc”.

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

def func(x):
    return x * 2

value = 3
result = func(value)
print(result)

a) 3
b) 8
c) 9
d) None

Correct answer is: b) 8
Explanation: The variable value is passed to the function func, and the function returns the value of x multiplied by 2. In this case, value is 4, so the function returns 4 * 2 = 8.

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

def func(x):
    if x == “”:
        return “Empty”
    else:
        return “Not empty”

result = func(“”)
print(result)

a) Empty
b) Not empty
c) Error
d) None

Correct answer is: a) Empty
Explanation: The function func checks if the input string x is empty. In this case, since x is an empty string, it returns “Empty”.

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

def func(x):
    return len(x)

result = func([1, 2, 3, 4])
print(result)

a) 1
b) 2
c) 3
d) 5

Correct answer is: d) 5
Explanation: The function func returns the length of the input list x using the “len()” function. In this case, the list has 4 elements, so the output is 4.

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

def func(x):
    return x[::-1]

result = func(“Python”)
print(result)

a) nohtyP
b) P
c) Python
d) None

Correct answer is: a) nohtyP
Explanation: The function func returns the reverse of the input string x using slicing with a step of -1. In this case, “Python” reversed becomes “nohtyP”.

Python Function MCQ : Set 1

Python Function MCQ

1). Which keyword is used to define a function in Python?

a) def
b) func
c) define
d) function

Correct answer is: a) def
Explanation: The keyword “def” is used to define a function in Python.

2). In a function what is the purpose of a return statement?

a) It defines the function name.
b) It calls another function.
c) It specifies the input parameters.
d) It returns a value from the function.

Correct answer is: d) It returns a value from the function.
Explanation: The return statement is used to specify the value that should be returned from the function when it is called.

3). Which of the following is a valid way to call a function in Python?

a) function_name()
b) functionName()
c) FunctionName()
d) All of the above.

Correct answer is: d) All of the above.
Explanation: All of the given options are valid ways to call a function in Python.

4). What is the purpose of the “pass” statement in Python?

a) It is used to define an empty function.
b) It is used to skip the execution of a function.
c) It is used to indicate the end of a function.
d) It is used to define a placeholder in a function.

Correct answer is: d) It is used to define a placeholder in a function.
Explanation: The “pass” statement is used as a placeholder when you want to define a function without any implementation.

5). Which scope in Python can access variables defined inside a function?

a) Global scope
b) Local scope
c) Built-in scope
d) None of the above

Correct answer is: a) Global scope
Explanation: Variables defined inside a function have local scope and can only be accessed within that function, unless they are explicitly marked as global.

6). What happens if a function is called with fewer arguments than specified in the function definition?

a) An error is raised.
b) The function will run without any issues.
c) The missing arguments will be assigned default values.
d) The function will return None.

Correct answer is: a) An error is raised.
Explanation: If a function is called with fewer arguments than specified in the function definition, a TypeError will be raised.

7). What is the purpose of the “lambda” keyword in Python?

a) It defines a lambda expression.
b) It is used to create a new function.
c) It is used to define the main function.
d) It is used to import external modules.

Correct answer is: a) It defines a lambda expression.
Explanation: The “lambda” keyword is used to define anonymous functions, also known as lambda expressions.

8). Which of the following is a valid way to pass arguments to a function?

a) Positional arguments
b) Keyword arguments
c) Default arguments
d) All of the above

Correct answer is: d) All of the above
Explanation: All the options (positional, keyword, and default arguments) are valid ways to pass arguments to a function.

9). What is the maximum number of return statements allowed in a function?

a) 1
b) 2
c) 3
d) There is no limit.

Correct answer is: d) There is no limit.
Explanation: There is no limit to the number of return statements in a function. However, only one return statement is executed during the function call.

10). What is the purpose of the “map” function in Python?

a) It applies a function to every item in an iterable.
b) It returns the maximum value from an iterable.
c) It converts an iterable to a list.
d) It sorts the items in an iterable.

Correct answer is: a) It applies a function to every item in an iterable.
Explanation: The “map” function is used to apply a given function to each item of an iterable and returns an iterator with the results.

11). Which of the following is a recursive function?

a) A function that calls itself.
b) A function that uses a loop.
c) A function that imports another module.
d) A function that returns multiple values.

Correct answer is: a) A function that calls itself.
Explanation: It is a function that calls itself either directly or indirectly.

12). Which built-in function is used to find the length of an object?

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

Correct answer is: d) len()
Explanation: The `len()` function is used to find the length of an object, such as a string, list, or tuple.

13). What is the purpose of the “global” keyword in Python?

a) It defines a global variable.
b) It imports a module.
c) It creates a new function.
d) It raises an error.

Correct answer is: a) It defines a global variable.
Explanation: The “global” keyword is used to indicate that a variable is defined in the global scope, allowing it to be accessed from any part of the program.

14). Which of the following is NOT a valid way to define a function in Python?

a) def my_function():
b) define my_function():
c) my_function = def():
d) lambda x: x + 1

Correct answer is: c) my_function = def():
Explanation: The option c) is not a valid way to define a function in Python. The correct syntax is `def function_name():`.

15). Which of the following is NOT a valid function call in Python?

a) my_function(1, 2)
b) my_function(x=1, y=2)
c) my_function(1, y=2)
d) my_function(x=1, 2)

Correct answer is: d) my_function(x=1, 2)
Explanation: In a function call, keyword arguments must follow positional arguments. In option d), a positional argument is followed by a keyword argument, which is not valid.

16). What is the purpose of the “__init__” method in a Python class?

a) It defines the class name.
b) It initializes the object’s state.
c) It imports external modules.
d) It defines class methods.

Correct answer is: b) It initializes the object’s state.
Explanation: The method “__init__” is a method in Python classes that is called when an object is created. It initializes the object’s state.

17). Which of the following is a built-in function in Python for sorting?

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

Correct answer is: b) sorted()
Explanation: The `sorted()` function is a built-in function in Python that is used to sort iterables, such as lists or tuples.

18). What is the purpose of the “isinstance()” function in Python?

a) It checks if two objects are equal.
b) It checks if an object is an instance of a class.
c) It converts an object to a different type.
d) It finds the index of an element in a list.

Correct answer is: b) It checks if an object is an instance of a class.
Explanation: The function `isinstance()` is used to check if an object is an instance of a specified class or its subclasses.

19). Which of the following is a valid way to define a default argument in a function?

a) def my_func(x = 0):
b) def my_func(x, default=0):
c) def my_func(default=0, x):
d) def my_func(x = 0, default):

Correct answer is: a) def my_func(x = 0):
Explanation: Option a) is a valid way to define a default argument in a function. The default value is specified after the “=” sign.

20). What is the purpose of the “enumerate()” function in Python?

a) It counts the number of occurrences of an element in an iterable.
b) It returns a reversed version of an iterable.
c) It assigns indices to items in an iterable.
d) It removes duplicates from an iterable.

Correct answer is: c) It assigns indices to items in an iterable.
Explanation: The “enumerate()” function is used to assign indices to items in an iterable, creating tuples of the form (index, item).

Python Set MCQ : Set 4

Python Set MCQ

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

a = {1, 2, 4, 5, 7, 8, 9}
print(“Original set1: “, a)
print(type(a))

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘set’>
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘list’>
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘tuple’>
d) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘dict’>

Correct answer is: a) Original set1: {1, 2, 4, 5, 7, 8, 9} \<class ‘set’>
Explanation: The code initializes a set named ‘a’ with the elements 1, 2, 4, 5, 7, 8, and 9. The print() function is then used to display the original set, which outputs {1, 2, 4, 5, 7, 8, 9}. The type() function is used to determine the data type of the set ‘a’, which is a set (class ‘set’).

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

a = {1, 2, 4, 5, 7, 8, 9}
print(“Original set1: “, a)
b = frozenset(a)
print(b)

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset({1, 2, 4, 5, 7, 8, 9})
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset([1, 2, 4, 5, 7, 8, 9])
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset((1, 2, 4, 5, 7, 8, 9))
d) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset({1: None, 2: None, 4: None, 5: None, 7: None, 8: None, 9: None})

Correct answer is: c) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset({1, 2, 4, 5, 7, 8, 9})
Explanation: The code initializes a set `a` with elements 1, 2, 4, 5, 7, 8, and 9. The line `b = frozenset(a)` creates a frozen set `b` from `a`. The `frozenset()` function returns an immutable frozenset object. The output will be “Original set1: {1, 2, 4, 5, 7, 8, 9}” followed by “frozenset({1, 2, 4, 5, 7, 8, 9})”.

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

a = {1,2,4,6}
b = {7,8,9,6}
c = {5,8,9}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Original set3: “,c)
print(“Difference between above sets: “)
print(a.difference(b.difference(c)))

a) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4}
b) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4, 6, 7, 8, 9}
c) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4, 5, 6, 7, 8, 9}
d) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {5, 7}

Correct answer is: a) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4}
Explanation: The code demonstrates the difference between sets using the difference() method. The difference() method is applied to the set ‘a’ with the argument ‘b.difference(c)’, which computes the difference between set ‘b’ and set ‘c’. Then, this difference is subtracted from set ‘a’ using the difference() method. The resulting set contains the elements that are present in ‘a’ but not in ‘b’ or ‘c’, which in this case is {1, 2, 4}.

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

a = {1,2,4,6}
b = {7,8,9,6}
c = {5,8,9,6}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Original set3: “,c)
print(“Intersection between above sets: “)
print(a.intersection(b.intersection(c)))

a) {6}
b) {1, 2, 4, 6}
c) {6, 8, 9}
d) {6, 8, 9, 5}

Correct answer is: a) {6}
Explanation: The code calculates the intersection between sets a, b, and c using the intersection() method. First, b.intersection(c) finds the common elements between sets b and c, which results in {6, 8, 9}. Then, a.intersection(b.intersection(c)) finds the common elements between set a and the result of the previous intersection, which is {6}.

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

a = {1,2,4,6}
b = {7,8,9,6}
c = {5,8,9,6}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Original set3: “,c)
print(“Difference between above sets: “)
print(a.union(b.union(c)))

a) {1, 2, 4, 5, 6, 7, 8, 9}
b) {1, 2, 4, 6, 7, 8, 9}
c) {1, 2, 4, 5, 6, 7}
d) {1, 2, 4, 6}

Correct answer is: a) {1, 2, 4, 5, 6, 7, 8, 9}
Explanation: The union() method is used to find the union of multiple sets. In this case, we are finding the union of set a, set b, and set c. The resulting set contains all the unique elements from all the sets involved. Therefore, the output will be {1, 2, 4, 5, 6, 7, 8, 9}.

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

String = “Learning python is fun”
Set = {“fun”,”python”}
count = 0
for word in Set:
    if word in String:
        count += 1
if count > 0:
print(“An element in a set is a substring of a given string”)
else:
print(“An element in a set is not a substring of a given string”)

a) An element in a set is a substring of a given string
b) An element in a set is not a substring of a given string
c) String: Learning python is fun
Set: {‘fun’, ‘python’}
d) String: “Learning python is fun”
Set: {“fun”,”python”}

Correct answer is: a) An element in a set is a substring of a given string
Explanation: The code checks if any element in the set is a substring of the given string. In this case, both “fun” and “python” are substrings of the string “Learning python is fun”. Therefore, the count variable is incremented, and the condition count > 0 is satisfied. As a result, the output will be “An element in a set is a substring of a given string”.

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

Set = {1, 2, 4, 6}
print(“Set: “, Set)
List = list(Set)
print(“The index of 4: “, List.index(4))

a) Set: {1, 2, 4, 6} | The index of 4: 2
b) Set: {1, 2, 4, 6} | The index of 4: 3
c) Set: [1, 2, 4, 6] | The index of 4: 2
d) Set: [1, 2, 4, 6] | The index of 4: 3

Correct answer is: a) Set: {1, 2, 4, 6} | The index of 4: 2
Explanation: The code initializes a set named “Set” with the elements 1, 2, 4, and 6. The set is then converted to a list using the list() function and stored in the variable “List”. When using the index() method on the list “List” and passing the argument 4, it returns the index position of the element 4, which is 2.

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

a = {1, 2, 4, 6}
print(“Original set:”, a)
Dict = {}
for ele in a:
    Dict[ele] = {}
print(“Dictionary:”, Dict)

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

Correct answer is: a) Original set: {1, 2, 4, 6} Dictionary: {1: {}, 2: {}, 4: {}, 6: {}}
Explanation: In the code, a set `a` is defined with elements [1, 2, 4, 6]. The set is then printed as “Original set: {1, 2, 4, 6}”. An empty dictionary `Dict` is created. The for loop iterates over each element in set `a` and assigns an empty dictionary as a value to each element in the `Dict` dictionary. Finally, the dictionary is printed as “Dictionary: {1: {}, 2: {}, 4: {}, 6: {}}”.

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

Set = set()
for num in range(1, 21):
    if num % 2 == 0:
        Set.add(num)
print(“Set of even numbers:”, Set)

a) Set of even numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
b) Set of even numbers: {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
c) Set of even numbers: {}
d) Set of even numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18}

Correct answer is: a) Set of even numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
Explanation: The given code initializes an empty set, `Set`. It then iterates over the numbers from 1 to 20 using a `for` loop. For each number, if the number is divisible by 2 (i.e., an even number), it adds the number to the set using the `add()` method. Finally, it prints the set of even numbers, which includes all even numbers from 1 to 20. The correct answer is option a.

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

Set = set()
for num in range(1,21):
    if num%2 != 0:
        Set.add(num)
print(“Set of odd numbers: “, Set)

a) Set of odd numbers: {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
b) Set of odd numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
c) Set of odd numbers: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
d) Set of odd numbers: {}

Correct answer is: a) Set of odd numbers: {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
Explanation: The code initializes an empty set and then iterates over numbers from 1 to 20. If a number is odd, it is added to the set using the add() method. Finally, the set is printed, showing the set of odd numbers from 1 to 20.

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

Set = {“Shan Rukh Khan”, “Akshay Kumar”, “Tom Hardy”, “Robert Pattinson”}
print(“Set of actors: “, Set)

a) Set of actors: {“Shan Rukh Khan”, “Akshay Kumar”, “Tom Hardy”, “Robert Pattinson”}
b) Set of actors: {“Shan Rukh Khan, Akshay Kumar, Tom Hardy, Robert Pattinson”}
c) Set of actors: {‘Shan Rukh Khan’, ‘Akshay Kumar’, ‘Tom Hardy’, ‘Robert Pattinson’}
d) Set of actors: [‘Shan Rukh Khan’, ‘Akshay Kumar’, ‘Tom Hardy’, ‘Robert Pattinson’]

Correct answer is: c) Set of actors: {‘Shan Rukh Khan’, ‘Akshay Kumar’, ‘Tom Hardy’, ‘Robert Pattinson’}
Explanation: The code defines a set named `Set` with four elements: “Shan Rukh Khan”, “Akshay Kumar”, “Tom Hardy”, and “Robert Pattinson”. When the `print()` function is called, it displays the set of actors enclosed in curly braces and single quotes.

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

Set1 = {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Set2 = {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
print(“Original Set1: “, Set1)
print(“Original Set2: “, Set2)
print(“Common books: “)
for book_name in Set1:
    if book_name in Set2:
        print(book_name)

a) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Lord of the Rings
b) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Lord of the Rings, The Magic Tree
c) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: The Magic Tree
d) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Wizards of Ice

Correct answer is: a) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Lord of the Rings
Explanation: The code compares the elements in Set1 with Set2 and prints the books that exist in both sets. In this case, “Lord of the Rings” is the only book that appears in both sets, so it will be printed as the common book.

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

Set = {“I”, “am”, “Learning”, “Python”}
max_len = 0
max_word = 0
print(“Original Set: “, Set)
for word in Set:
    if len(word) > max_len:
        max_len = len(word)
        max_word = word
print(“Word having maximum length: “, max_word)
print(“Length of the word: “, max_len)

a) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Learning”
Length of the word: 8
b) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Python”
Length of the word: 6
c) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Learning”
Length of the word: 7
d) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “am”
Length of the word: 2

Correct answer is: a) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Learning”
Length of the word: 8
Explanation: The code initializes the `Set` variable with a set of strings. It then iterates over each word in the set and checks if the length of the current word is greater than the current maximum length (`max_len`). If it is, it updates `max_len` and stores the current word as `max_word`. After the loop, it prints the original set, the word with the maximum length, and the length of that word.

14). 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(“b is subset of a”)
else:
    print(“b is not a subset of a”)

a) Original set1: {1, 2, 4, 5} Original set2: {2, 4} \n b is subset of a
b) Original set1: {1, 2, 4, 5} Original set2: {2, 4} \n b is not a subset of a
c) Original set1: {2, 4} Original set2: {1, 2, 4, 5} \n b is subset of a
d) Original set1: {2, 4} Original set2: {1, 2, 4, 5} \n b is not a subset of a

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {2, 4} \n b is a subset of a
Explanation: The code checks if every element in set b is also present in set a. If all elements in b are found in a, then b is considered a subset of a. Otherwise, it is not a subset. In this case, set a contains the elements [1, 2, 4, 5] and set b contains the elements [2, 4]. Since all elements in b (2 and 4) are present in a, the condition count == len(b) is satisfied, and the output is “b is a subset of a”.

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

a = {1,2,4,5}
b = {7,8,9}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Are two sets dis-joint: “,a.isdisjoint(b))

a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: True
b) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: False
c) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: None
d) Error: The code contains a syntax error.

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: True
Explanation: The code initializes two sets, a and b, with the values {1, 2, 4, 5} and {7, 8, 9} respectively. The isdisjoint() method is then used to check if the two sets are disjoint (have no common elements). In this case, the sets have no common elements, so the output will be True.

16). 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(“b is subset of a: “, b.issubset(a))

a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: True
b) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: False
c) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: None
d) Error: Invalid syntax in the code.

Correct answer is: a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: True
Explanation: The code defines two sets, `a` and `b`. `a` contains elements [1, 2, 4, 5], while `b` contains elements [2, 4]. The `issubset()` method is then used to check if `b` is a subset of `a`. Since all elements of `b` are present in `a`, the output is `True`.

17). Which statement is used to check if an element exists in a set?

a) if element in set:
b) if element exists(set):
c) if element.has(set):
d) if element.exists(set):

Correct answer is: a) if element in set:
Explanation: The “in” keyword is used to check if an element exists in a set.

18). What is the result of executing the following code:

set = {1, 2, 3}
print(2 in set)?

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

Correct answer is: a) True
Explanation: The “in” keyword checks if the element 2 exists in the set, which returns True.

19). Which method is used to return the maximum element from a set?

a) max()
b) maximum()
c) largest()
d) get_max()

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

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

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

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

Correct answer is: c) Original set: {1, 2, 4, 5, 7, 8, 9} New set: {1, 2, 4, 5}
Explanation: The code starts with a set `a` containing elements {1, 2, 4, 5, 7, 8, 9}. It then defines another set `b` with elements {7, 8, 9}. The code then iterates over each element in `b` and checks if it exists in `a`. If an element is found in `a`, it is removed using the `remove()` method. After this process, the code prints the updated set `a`.

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

a = {1, 2, 4, 5, 7, 8, 9}
print(“Original set1: “,a)
if len(a) == 0:
    print(“Set is empty”)
else:
    print(“Set is not empty”)

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
Set is empty
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Set is not empty
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
Error: Set object has no attribute ’empty’
d) Original set1: {1, 2, 4, 5, 7, 8, 9}
Error: Set object has no attribute ‘len’

Correct answer is: b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Set is not empty
Explanation: The code initializes a set a with elements [1, 2, 4, 5, 7, 8, 9]. The len(a) function returns the number of elements in the set, which is not equal to 0 in this case. Therefore, the condition len(a) == 0 evaluates to False. As a result, the code executes the else block and prints “Set is not empty”

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

a = {1, 2, 4, 5, 7, 8, 9}
b = {2,3,4}
print(“Original set1: “,a)
print(“Original set2: “,b)
if a == b:
   print(“Both sets are equal”)
else:
    print(“Both sets are not equal”)

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Both sets are equal
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Both sets are not equal
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Error: Invalid comparison between sets
d) Error: Invalid syntax

Correct answer is: b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Both sets are not equal
Explanation: The code compares two sets, a and b, using the equality operator (==). Since the sets have different elements (set a has elements {1, 2, 4, 5, 7, 8, 9} and set b has elements {2, 3, 4}), the condition evaluates to False and the statement “Both sets are not equal” is printed.

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]}`.