Python Dictionary MCQ : Set 2

Python Dictionary MCQ

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

print(dict1)

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

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

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

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

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

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

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

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

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

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

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

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

string = “SQAToolss”
dict1 = {}

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

print(dict1)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

n = 4
D1 = {}

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

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

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

Python Dictionary MCQ : Set 1

Python Dictionary MCQ

1). What is a dictionary in Python?

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

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

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

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

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

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

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

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

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

4). Can a dictionary contain duplicate keys?

a) Yes
b) No

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Python Tuple MCQ : Set 4

Python Tuple MCQ

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Python Tuple MCQ : Set 3

Python Tuple MCQ

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Corresct answer is: a). Original list of tuples: [(4, 5, 6), (6,), (2, 3), (6, 7, 8, 9, 0)]
After sorting list of tuples by length of tuples: [(6,), (2, 3), (4, 5, 6), (6, 7, 8, 9, 0)]
Explanation: The code sorts the list of tuples `l` based on the length of each tuple using the `sorted()` function and a lambda function as the `key` parameter. The resulting sorted list of tuples will be `[(6,), (2, 3), (4, 5, 6), (6, 7, 8, 9, 0)]`.

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

tup = (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
print(“Original tuple: “, tup)
d = {}
for char in tup:
    if char not in d:
        d[char] = 0
    if char in d:
        d[char] += 1
print(“Frequency count: “, d)

a). Original tuple: (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
Frequency count: {‘a’: 2, ‘b’: 3, ‘c’: 1, ‘d’: 1}
b). Original tuple: (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
Frequency count: {‘a’: 2, ‘b’: 2, ‘c’: 1, ‘d’: 1}
c). Original tuple: (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
Frequency count: {‘a’: 3, ‘b’: 3, ‘c’: 1, ‘d’: 1}
d). Original tuple: (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
Frequency count: {‘a’: 1, ‘b’: 2, ‘c’: 1, ‘d’: 1}

Corresct answer is: a). Original tuple: (‘a’, ‘b’, ‘c’, ‘d’, ‘b’, ‘a’, ‘b’)
Frequency count: {‘a’: 2, ‘b’: 3, ‘c’: 1, ‘d’: 1}
Explanation: The code iterates over each character in the tuple tup and updates the dictionary d with the frequency count of each character.

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

l = [(1,4),(4,5,6),(2,),(7,6,8,9),(3,5,6,0,1)]
l1 = []
print(“Original list of tuples: “, l)
for tup in l:
    if len(tup)>3:
        l1.append(tup)
print(“After removing tuples: “, l1)

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

Corresct answer is: c). Original list of tuples: [(1,4),(4,5,6),(2,),(7,6,8,9),(3,5,6,0,1)]
After removing tuples: [(7,6,8,9),(3,5,6,0,1)]
Explanation: The code iterates over each tuple in the list l and checks if the length of the tuple is greater than 3. If it is, the tuple is appended to the list l1. The original list of tuples is [(1,4),(4,5,6),(2,),(7,6,8,9),(3,5,6,0,1)], and after removing tuples with length greater than 3, the updated list is [(4,5,6),(7,6,8,9),(3,5,6,0,1)].

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

l = [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
print(“Original list of tuples: “,l)
d = {}
for tup in l:
    if tup not in d:
        d[tup] = 0
    if tup in d:
        d[tup] += 1
print(“Frequency count : “,d)

a). Original list of tuples: [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
Frequency count: {(‘s’,’q’): 2, (‘t’,’o’,’o’,’l’): 1, (‘p’,’y’): 1}
b). Original list of tuples: [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
Frequency count: {(‘s’,’q’): 1, (‘t’,’o’,’o’,’l’): 1, (‘p’,’y’): 1}
c). Original list of tuples: [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
Frequency count: {(‘s’,’q’): 1, (‘t’,’o’,’o’,’l’): 2, (‘p’,’y’): 1}
d). Original list of tuples: [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
Frequency count: {(‘s’,’q’): 2, (‘t’,’o’,’o’,’l’): 2, (‘p’,’y’): 1}

Corresct answer is: a). Original list of tuples: [(‘s’,’q’),(‘t’,’o’,’o’,’l’),(‘p’,’y’),(‘s’,’q’)]
Frequency count: {(‘s’,’q’): 2, (‘t’,’o’,’o’,’l’): 1, (‘p’,’y’): 1}
Explanation: The code initializes an empty dictionary d). It then iterates over each tuple tup in the list l. If the tuple tup is not already in the dictionary d, it adds it with a value of 0. Then, it increments the value of tup in d by 1. The final d dictionary contains the frequency count of each tuple in the list.

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

tup = (1, 2, 3, 4)
if len(set(tup)) == len(tup):
    print(“Tuple is distinct”)
else:
    print(“Tuple is not distinct”)

a). Tuple is distinct
b). Tuple is not distinct
c). Error: invalid syntax
d). Error: unsupported operand type(s)

Corresct answer is: a). Tuple is distinct
Explanation: The code snippet checks whether the given tuple tup is distinct or not. It does so by converting the tuple to a set using the set() function, which removes any duplicate elements since sets only contain unique elements. The len() function is then used to compare the lengths of the original tuple and the set. If the lengths are equal, it means that all elements in the tuple are distinct. 

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

tup1 = (3, 4, 5, 4, 6, 3)
if len(set(tup1)) == len(tup1):
    print(“Tuple is distinct”)
else:
    print(“Tuple is not distinct”)

a). “Tuple is distinct”
b). “Tuple is not distinct”
c). Error: invalid syntax
d). Error: undefined variable ‘tup1’

Corresct answer is: b). “Tuple is not distinct”
Explanation: The code checks if the length of the set created from tup1 is equal to the length of tup1. If they are not equal, it means there are duplicate elements in the tuple, and the output will be “Tuple is not distinct.”

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

tup = (4, 1, 7, 5)
print(“Original tuple: “, tup)
tup1 = str(tup)
print(“After converting to a string: “, tup1)
print(“Type of new tuple: “, type(tup1))

a). Original tuple: (4, 1, 7, 5)
After converting to a string: (4, 1, 7, 5)
Type of new tuple: tuple
b). Original tuple: (4, 1, 7, 5)
After converting to a string: (4, 1, 7, 5)
Type of new tuple: <class ‘str’>
c). Original tuple: [4, 1, 7, 5]
After converting to a string: ‘4, 1, 7, 5’
Type of new tuple: list
d). Original tuple: (4, 1, 7, 5)
After converting to a string: [4, 1, 7, 5]
Type of new tuple: list

Corresct answer is: b). Original tuple: (4, 1, 7, 5)
After converting to a string: (4, 1, 7, 5)
Type of new tuple: <class ‘str’>
Explanation: In the given code, the tuple `tup` is converted to a string using the `str()` function. The resulting string will be (4, 1, 7, 5). The `type()` function is used to determine the type of the variable `tup1`, which will be `str`.

Python Tuple MCQ : Set 2

Python Tuple MCQ

1). Which of the following methods is used to insert an element at a specific index in a tuple?

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

Correct answer is: a
Explanation: There is no built-in method to insert an element at a specific index in a tuple because tuples are immutable.

2). Can a tuple be converted into a string using the `str()` function?

a) Yes
b) No

Correct answer is: a
Explanation: The `str()` function can be used to convert a tuple into a string representation.

3). Which method is used to remove a specific element from a tuple?

a) remove()
b) delete()
c) discard()
d) Tuples are immutable and cannot be modified)

Correct answer is: d
Explanation: Tuples are immutable, so elements cannot be removed directly.

4). Which of the following statements about tuples is false?

a) Tuples are enclosed in parentheses.
b) Tuples can be used as keys in dictionaries.
c) Tuples are immutable.
d) Tuples can contain elements of different data types.

Correct answer is: d
Explanation: Tuples can contain elements of different data types, so option (d) is false.

5). Which of the following methods is used to convert a list into a tuple?

a) to_tuple()
b) convert_tuple()
c) tuple()
d) list_to_tuple()

Correct answer is: c
Explanation: The `tuple()` function is used to convert a list into a tuple.

6). Which of the following methods is used to find the index of the last occurrence of a specific element in a tuple?

a) count()
b) find()
c) index()
d) rindex()

Correct answer is: d
Explanation: The `rindex()` method is used to find the index of the last occurrence of a specific element in a tuple.

7). Which of the following statements is true regarding tuple unpacking?

a) Tuple unpacking allows assigning multiple variables from a single tuple.
b) Tuple unpacking can only be done with tuples of the same length.
c) Tuple unpacking is not supported in Python.
d) Tuple unpacking is used to merge two tuples into one.

Correct answer is: a
Explanation: Tuple unpacking allows assigning multiple variables from a single tuple, making option (a) true.

8).  Can a tuple be modified after it is created?

a) Yes
b) No

Correct answer is: b
Explanation: Tuples are immutable, meaning they cannot be modified after creation.

9). Which of the following methods is used to check if all elements in a tuple are of the same value?

a) same()
b) equal()
c) all_equal()
d) None of the above

Correct answer is: a
Explanation: The method same() does not exist in Python. To check if all elements in a tuple are of the same value, we can compare the first element with the rest of the elements using the all() function.

10). Which of the following methods is used to find the minimum value in a tuple?

a) min()
b) minimum()
c) smallest()
d) None of the above

Correct answer is: a
Explanation: The min() function is used to find the minimum value in a tuple. It returns the smallest element based on their natural ordering.

11). Can a tuple be used as a key in a set?

a) Yes
b) No

Correct answer is: b
Explanation: No, a tuple cannot be used as a key in a set. Sets require elements to be hashable, and since tuples are mutable, they are not hashable.

12).  Which method is used to find the maximum value in a tuple?

a) max()
b) maximum()
c) largest()
d) None of the above

Correct answer is: a
Explanation: The max() function is used to find the maximum value in a tuple. It returns the largest element based on their natural ordering.

13). Can a tuple contain mutable objects like lists?

a) Yes
b) No

Correct answer is: a
Explanation: Yes, a tuple can contain mutable objects like lists. However, the tuple itself remains immutable, but the objects it contains can be mutable.

14). Which of the following methods is used to find the length of a tuple?

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

Correct answer is: d
Explanation: The built-in len() function is used to find the length of a tuple. It returns the number of elements in the given tuple.

15). Can a tuple be used as an element in another tuple?

a) Yes
b) No

Correct answer is: a
Explanation: Yes, a tuple can be used as an element in another tuple. Tuples can contain elements of any data type, including other tuples.

16). Which method is used to convert a tuple into a set?

a) set()
b) convert_set()
c) to_set()
d) None of the above

Correct answer is: a
Explanation: The set() function can be used to convert a tuple into a set. It creates a new set containing the unique elements from the tuple.

17). Which of the following statements is true regarding the memory efficiency of tuples compared to lists?

a) Tuples are more memory-efficient than lists.
b) Lists are more memory-efficient than tuples.
c) Tuples and lists have the same memory efficiency.
d) Memory efficiency does not depend on the data structure.

Correct answer is: c
Explanation: Tuples and lists have the same memory efficiency in terms of storing elements. The memory consumption depends on the number and size of the elements, not the data structure itself.

18). Can a tuple be sorted using the `sort()` method?

a) Yes
b) No

Correct answer is: b
Explanation: No, tuples are immutable, and the sort() method is only available for mutable sequences like lists. To sort a tuple, you can convert it to a list, sort the list, and then convert it back to a tuple.

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

tup = (41, 15, 69, 55)
print(“Maximum value: “, max(tup))

a). Maximum value: 41
b). Maximum value: 69
c). Maximum value: 55
d). Maximum value: 15

Corresct answer is: b) Maximum value: 69
Explanation: The max() function returns the maximum value from the given sequence. In this case, the sequence is the tuple tup containing the values (41, 15, 69, 55). The maximum value in the tuple is 69, so the output will be “Maximum value: 69”.

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

tup = (36, 5, 79, 25)
print(“Minimum value: “, min(tup))

a). Minimum value: 36
b). Minimum value: 5
c). Minimum value: 79
d). Minimum value: 25

Corresct answer is: b) Minimum value: 5
Explanation: The min() function returns the minimum value from a sequence. In this case, the sequence is the tuple tup containing the values (36, 5, 79, 25). The smallest value in the tuple is 5, so the output will be “Minimum value: 5”.

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

list1 = [4, 6, 8]
list2 = [7, 1, 4]
tup = tuple(zip(list1, list2))
print(tup)

a). [(4, 7), (6, 1), (8, 4)]
b). [(7, 4), (1, 6), (4, 8)]
c). [(4, 6, 8), (7, 1, 4)]
d). [(4, 7), (6, 1), (8, 4), (0, 0)]

Corresct answer is: a). [(4, 7), (6, 1), (8, 4)]
Explanation: The zip() function takes two or more iterables and aggregates their elements into tuples. In this case, it combines the elements of list1 and list2 into tuples. The output will be [(4, 7), (6, 1), (8, 4)].

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

list1 = [4, 6, 3, 8]
tup = [(val, pow(val, 3)) for val in list1]
print(tup)

a). `[(4, 64), (6, 216), (3, 27), (8, 512)]`
b). `[(4, 12), (6, 18), (3, 9), (8, 24)]`
c). `[(64, 4), (216, 6), (27, 3), (512, 8)]`
d). `[(12, 4), (18, 6), (9, 3), (24, 8)]`

Corresct answer is: a). `[(4, 64), (6, 216), (3, 27), (8, 512)]`

Explanation: The code snippet demonstrates list comprehension and uses the `pow()` function to calculate the cube of each value in the `list1` list. The resulting list comprehension creates a new list of tuples, where each tuple consists of the original value from `list1` and its cube. The output will be `[(4, 64), (6, 216), (3, 27), (8, 512)]`.

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

tup = (4, 8, 9, 1)
print(“Number in the tuple with index 2: “, tup[2])

a). Number in the tuple with index 2: 4
b). Number in the tuple with index 2: 8
c). Number in the tuple with index 2: 9
d). Number in the tuple with index 2: 1

Corresct answer is: c). Number in the tuple with index 2: 9
Explanation: The code defines a tuple `tup` with elements (4, 8, 9, 1). The index starts from 0, so `tup[2]` accesses the element at index 2, which is 9. Therefore, the output will be “Number in the tuple with index 2: 9”.

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

tup = (6, 7, 3)
(a, b, c) = tup
print(“a: “, a)
print(“b: “, b)
print(“c: “, c)

a). a: 6, b: 7, c: 3
b). a: 7, b: 3, c: 6
c). a: 6, b: 3, c: 7
d). a: 7, b: 6, c: 3

Corresct answer is: a). a: 6, b: 7, c: 3
Explanation: In the given code, the tuple tup contains three elements: 6, 7, and 3. The variables a, b, and c are assigned the values of the corresponding elements in the tuple using tuple unpacking. Therefore, a will be 6, b will be 7, and c will be 3.

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

tup = (18, 65, 3, 45)
print(“Old tuple: “, tup)
tup = list(tup)
tup.append(15)
tup = tuple(tup)
print(“New tuple: “, tup)

a). Old tuple: (18, 65, 3, 45)
New tuple: (18, 65, 3, 45, 15)
b). Old tuple: (18, 65, 3, 45)
New tuple: (18, 65, 3, 45)
c). Old tuple: [18, 65, 3, 45]
New tuple: (18, 65, 3, 45, 15)
d). Old tuple: [18, 65, 3, 45]
New tuple: [18, 65, 3, 45, 15]

Corresct answer is: c). Old tuple: [18, 65, 3, 45]
New tuple: (18, 65, 3, 45, 15)
Explanation: The code first converts the tuple tup to a list using the list() function. Then, the number 15 is appended to the list. Finally, the list is converted back to a tuple using the tuple() function. Therefore, the output will be:
Old tuple: [18, 65, 3, 45]
New tuple: (18, 65, 3, 45, 15)

Python Tuple MCQ : Set 1

Python Tuple MCQ

1). What is a tuple in Python?

a) A mutable data type
b) An immutable data type
c) A collection of key-value pairs
d) A dynamic array

Correct answer is: b
Explanation: A tuple is an immutable data type in Python, meaning its elements cannot be modified once defined

2). Which of the following is the correct way to define a tuple in Python?

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

Correct answer is: c
Explanation: Tuples are defined using parentheses in Python, as shown in option (c)

3). Which of the following operations is not supported on tuples?

a) Accessing elements by index
b) Modifying elements
c) Concatenating two tuples
d) Slicing

Correct answer is: b
Explanation: Tuples are immutable, so modifying elements is not supported) Options (a), (c), and (d) are valid operations on tuples.

4). How can you access the second element of a tuple named “tuple”?

a) tuple[1]
b) tuple(1)
c) tuple[2]
d) tuple(2)

Correct answer is: a
Explanation: In Python, indexing starts from 0, so the second element can be accessed using tuple[1].

5). Which of the following statements is true about tuples?

a) Tuples can contain elements of different data types.
b) Tuples can be resized after creation.
c) Tuples preserve the order of elements.
d) Tuples can be used as keys in dictionaries.

Correct answer is: c
Explanation: Tuples preserve the order of elements, making them suitable for situations where element order is important, such as storing coordinates.

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

mtuple = (1, 2, 3)
print(uple[0:2])

a) (1, 2)
b) (2, 3)
c) (2, 3)
d) (1, 2, 3)

Correct answer is: a
Explanation: Slicing the tuple from index 0 to 2 (exclusive) will result in (1, 2).

7). Which method can be used to find the number of occurrences of a specific element in a tuple?

a) count()
b) find()
c) index()
d) len()

Correct answer is: a
Explanation: The `count()` method is used to find the number of occurrences of a specific element in a tuple.

8). Can tuples be nested within other tuples in Python?

a) Yes
b) No

Correct answer is: a
Explanation: Tuples can be nested within other tuples in Python, allowing the creation of more complex data structures.

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

tuple = (1, 2, 3) * 2
print(tuple)

a) (1, 2, 3)
b) (2, 4, 6)
c) (1, 2, 3, 1, 2, 3)
d) (1, 1, 2, 2, 3, 3)

Correct answer is: c
Explanation: The `*` operator duplicates the tuple, resulting in (1, 2, 3, 1, 2, 3).

10). Which of the following is not a valid way to iterate over a tuple in Python?

a) Using a for loop
b) Using the `enumerate()` function
c) Using the `iter()` function
d) Using a while loop

Correct answer is: d
Explanation: A while loop is not a valid way to iterate over a tuple directly. Other options (a), (b), and (c) are valid)

11). Which of the following statements is true regarding the memory consumption of tuples and lists?

a) Tuples consume less memory than lists.
b) Lists consume less memory than tuples.
c) Tuples and lists consume the same amount of memory.
d) Memory consumption depends on the number of elements, not the data type.

Correct answer is: a
Explanation: Tuples consume less memory than lists because they are immutable and have a fixed size.

12). Which method is used to convert a tuple into a list?

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

Correct answer is: c
Explanation: The `list()` function is used to convert a tuple into a list.

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

tuple = (‘SQATOOLS’,)
print(type(tuple))

a) <class ‘tuple’>
b) <class ‘list’>
c) <class ‘str’>
d) <class ‘set’>

Correct answer is: a
Explanation: The comma after ‘SQATOOLS’ indicates that this is a tuple, so the output will be <class ‘tuple’>.

14). Which of the following is the correct way to compare two tuples for equality in Python?

a) tuple1 == tuple2
b) tuple1.equals(tuple2)
c) tuple1.compare(tuple2)
d) tuple1 is tuple2

Correct answer is: a
Explanation: The `==` operator is used to compare two tuples for equality.

15). Can tuples contain mutable elements like lists or dictionaries?

a) Yes
b) No

Correct answer is: a
Explanation: Tuples can contain mutable elements like lists or dictionaries, but the tuple itself remains immutable.

16). Which method is used to sort a tuple in ascending order?
a) sort()
b) sorted()
c) sort_asc()
d) order()

Correct answer is: b
Explanation: The `sorted()` function is used to sort a tuple in ascending order.

17). Which method is used to find the index of the first occurrence of a specific element in a tuple?
a) count()
b) find()
c) index()
d) position()

Correct answer is: c
Explanation: The `index()` method in Python is used to find the index of the first occurrence of a specific element in a tuple.

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

tuple = (4, 5, 6)
a, b, c = tuple
print(b)

a) 4
b) 5
c) 6
d) Error: too many values to unpack

Correct answer is: b
Explanation: The tuple elements are assigned to variables a, b, and c, respectively. Printing b will give the output 5.

19). Which of the following is a valid way to delete an entire tuple in Python?

a) del my_tuple
b) my_tuple.clear()
c) my_tuple.delete()
d) my_tuple = ()

Correct answer is: a
Explanation: The `del` keyword is used to delete an entire tuple in Python.

20). Which of the following methods is used to reverse the order of elements in a tuple?

a) reverse()
b) reversed()
c) invert()
d) flip()

Correct answer is: b
Explanation: The `reversed()` function is used to reverse the order of elements in a tuple.

21). Can a tuple be used as a key in a dictionary?

a) Yes
b) No

Correct answer is: a
Explanation: Tuples can be used as keys in dictionaries because they are immutable.

22). Which of the following methods is used to check if an element exists in a tuple?

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

Correct answer is: d
Explanation: The `in` keyword is used to check if an element exists in a tuple.

23). Which of the following statements is true regarding the ordering of elements in a tuple?

a) Tuples are unordered)
b) Tuples maintain the order in which elements were added)
c) The order of elements in a tuple is random.
d) The order of elements in a tuple depends on their values.

Correct answer is: b
Explanation: Tuples maintain the order in which elements were added, preserving the sequence of elements.

24). Which method is used to concatenate two tuples?

a) add()
b) concatenate()
c) extend()
d) +

Correct answer is: d
Explanation: The `+` operator can be used to concatenate two tuples.

25). Can a tuple contain duplicate elements?

a) Yes
b) No

Correct answer is: a
Explanation: Tuples can contain duplicate elements.

Python String MCQ : Set 4

Python String MCQ

1). What does the following code do?

string1 = “I want to eat fast food”
print(“Occurrences of food: “, string1.count(“food”))

a) It prints the number of occurrences of the word “food” in the string.
b) It counts the number of words in the string.
c) It checks if the word “food” is present in the string.
d) It replaces the word “food” with another word in the string.

Correct answer is: a) It prints the number of occurrences of the word “food” in the string.
Explanation: The count() method is used to count the number of occurrences of a substring in a string. In this case, it counts the number of occurrences of the word “food” and the result is printed.

2). What will be the output of the code snippet?

string = “We are learning python”

for word in string.split(” “):
    if len(word) > 3:
print(word, end=” “)

a) We are learning python
b) learning python
c) We are
d) are learning python

Correct answer is: b) learning python
Explanation: The code prints only the words from the given string that have a length greater than 3. In this case, “learning” and “python” are the only words that satisfy the condition, so they will be printed.

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

import re
string = “qwerty”

result = re.split(‘a|e|i|o|u’, string)
print(” “.join(result))

a) q w r t y
b) qw rty
c) qwerty
d) qwer ty

Correct answer is: b) qw rty
Explanation: The code splits the string at every occurrence of the vowels ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’. The resulting substrings are stored in the result list. The join() method is used to concatenate the substrings with a space in between, resulting in “qw rty”.

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

string = “I’m learning python at Sqatools”
List = string.split(” “)

for i in range(len(List)):
    if List[i] == “python”:
        List[i] = “SQA”
    elif List[i] == “Sqatools”:
        List[i] = “TOOLS”
print(” “.join(List))

a) I’m learning python at Sqatools
b) I’m learning SQA at TOOLS
c) I’m learning SQA at Sqatools
d) I’m learning python at TOOLS

Correct answer is: b) I’m learning SQA at TOOLS
Explanation: The code splits the string into a list of words using the space delimiter. It then iterates over each word in the list. If the word is “python”, it replaces it with “SQA”. If the word is “Sqatools”, it replaces it with “TOOLS”. Finally, it joins the modified list of words back into a string with spaces. Therefore, the output will be “I’m learning SQA at TOOLS”.

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

string = “Sqatool python”
new_str = “”

for char in string:
    if char == “a”:
        new_str += “1”
    elif char == “t”:
        new_str += “2”
    elif char == “o”:
        new_str += “3”
    else:
        new_str += char
print(new_str)

a) Sq1t22l pyth3n
b) Sq1233l py2h3n
c) Sqatool pyth3n
d) Sqa2ool python

Correct answer is: b) Sq1233l py2h3n
Explanation: The code iterates over each character in the given string. If the character is ‘a’, it replaces it with ‘1’. If the character is ‘t’, it replaces it with ‘2’. If the character is ‘o’, it replaces it with ‘3’. Otherwise, it keeps the original character. The final value of new_str is “Sq1233l py2h3n”.

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

List1 = [“Python”, ” “, ” “, “sqatools”]
List2 = []

for string in List1:
    if string != ” “:
        List2.append(string)
print(List2)

a) [“Python”, “sqatools”]
b) [“Python”, “”, “sqatools”]
c) [“Python”, ” “, ” “, “sqatools”]
d) []

Correct answer is: a) [“Python”, “sqatools”]
Explanation: The code iterates over each element in List1. If the element is not equal to a single space ” “, it is appended to List2. The elements “Python” and “sqatools” are not equal to a space, so they are added to List2. The resulting list is [“Python”, “sqatools”].

7). What will be the value of string2 after executing the code snippet?

string1 = “Sqatools : is best, for python”
string2 = “”
punc = ”’!()-[]{};:'”\,<>./?@#$%^&*_~”’

for char in string1:
    if char not in punc:
        string2 += char

a) “Sqatools : is best, for python”
b) “Sqatools is best for python”
c) “Sqatools:isbestforpython”
d) “Sqatools : is best for python”

Correct answer is: b) “Sqatools is best for python”
Explanation: The code removes all punctuation characters from string1 and stores the modified string in string2. The punctuation characters in string1 are “:, “. Therefore, the resulting string will be “Sqatools is best for python” with no spaces after “:”.

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

string = “hello world”
list1 = []

for char in string:
    if string.count(char) > 1:
        list1.append(char)
print(set(list1))

a) {‘l’, ‘o’}
b) {‘e’, ‘l’, ‘o’, ‘r’}
c) {‘o’}
d) {‘l’}

Correct answer is: a) {‘l’, ‘o’}
Explanation: In the given string, both ‘l’ and ‘o’ appear more than once. Therefore, the set() function removes duplicates, resulting in the set of characters {‘l’, ‘o’} being printed.

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

string1 = “iamlearningpythonatsqatools”
string2 = “pystlmi”
string3 = set(string1)
count = 0

for char in string3:
    if char in string2:
        count += 1

if count == len(string2):
    print(True)
else:
    print(False)

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

Correct answer is: a) True
Explanation: The code checks if all characters in string2 are present in string1. Since all characters in string2 are found in string1, the condition count == len(string2) evaluates to True, and therefore, the output is True.

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

string = “xyabkmp”
print(“”.join(sorted(string)))

a) “xyabkmp”
b) “mpkba”
c) “abkmpxy”
d) “pkmabxy”

Correct answer is: b) “abkmpxy”
Explanation: The code sorts the characters in the string alphabetically using the `sorted()` function and then joins the sorted characters together using the `””.join()` method. So, the output will be the string “abkmpxy” with the characters in alphabetical order.

11). What does the following code snippet do?

import random

result = ” “
for i in range(9):
    val = str(random.randint(0, 1))
    result += val
print(result)

a) Generates a random string of 9 characters consisting of numbers between 0 and 9.
b) Generates a random string of 9 characters consisting of numbers 0 and 1.
c) Generates a random string of 9 characters consisting of lowercase alphabets.
d) Generates a random string of 9 characters consisting of uppercase alphabets.

Correct answer is: b) Generates a random string of 9 characters consisting of numbers 0 and 1.
Explanation: The code imports the random module and initializes an empty string variable called “result”. It then enters a loop that iterates 9 times. In each iteration, it generates a random integer using `random.randint(0, 1)`, which will either be 0 or 1. This random integer is converted to a string using `str()`. The resulting string is then concatenated with the “result” variable.

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

str1 = “abab”
test = []

for i in range(len(str1)):
    for j in range(i+1,len(str1)+1):
        test.append(str1[i:j])

dict1 = dict()
for val in test:
    dict1[val] = str1.count(val)
print(dict1)

a) {‘a’: 2, ‘ab’: 2, ‘aba’: 1, ‘abab’: 1, ‘b’: 2, ‘ba’: 1, ‘bab’: 1}
b) {‘a’: 4, ‘b’: 4, ‘ab’: 2, ‘ba’: 2}
c) {‘ab’: 2, ‘aba’: 1, ‘abab’: 1, ‘b’: 2, ‘ba’: 1, ‘bab’: 1}
d) {‘a’: 4, ‘b’: 4}

Correct answer is: a) {‘a’: 2, ‘ab’: 2, ‘aba’: 1, ‘abab’: 1, ‘b’: 2, ‘ba’: 1, ‘bab’: 1}
Explanation: The code generates all possible substrings of the string “abab” and stores them in the list `test`. Then, a dictionary `dict1` is created where the keys are the substrings and the values are the count of each substring in the original string. The output is the resulting dictionary.

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

string = “Sqatools”
print(“The index of q is: “, string.index(“q”))

a) The index of q is: 1
b) The index of q is: 2
c) The index of q is: 3
d) The index of q is: 4

Correct answer is: a) The index of q is: 1
Explanation: The index() method returns the index of the first occurrence of the specified substring within the string. In this case, the letter “q” is located at index 1 in the string “Sqatools”.

14). Which method is used to remove leading and trailing characters from a string?

a) remove()
b) trim()
c) strip()
d) clean()

Correct answer is: c) strip()
Explanation: The strip() method is used to remove leading and trailing characters from a string.

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

string = ” sqaltoolspythonfun “
print(string.strip())

a) “sqaltoolspythonfun”
b) ” sqaltoolspythonfun”
c) “sqaltoolspythonfun “
d) ” sqaltoolspythonfun “

Correct answer is: a) “sqaltoolspythonfun”
Explanation: The strip() method removes leading and trailing whitespace characters from a string. In this case, the leading and trailing spaces are removed, resulting in “sqaltoolspythonfun”.

16). What is the value of the string variable after executing the given code?

string = “sqa,tools.python”
string.replace(“,”,”.”)

a) “sqa.tools.python”
b) “sqa,tools,python”
c) “sqa.tools,python”
d) “sqa.tools.python”

Correct answer is: a) “sqa.tools.python”
Explanation: The replace() method replaces all occurrences of the specified substring (“,”) with another substring (“.”). In this case, the comma (“,”) is replaced with a dot (“.”).

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

str1 = “l,e,a,r,n,I,n,g,p,y,t,h,o,n”
print(str1.rsplit(‘,’, 1))

a) [‘l,e,a,r,n,I,n,g,p,y,t,h’, ‘o,n’]
b) [‘l,e,a,r,n,I,n,g,p,y,t,h,o’, ‘n’]
c) [‘l,e,a,r,n,I,n,g,p,y,t,h’, ‘o’, ‘n’]
d) [‘l,e,a,r,n,I,n,g,p,y,t,h,o,n’]

Correct answer is: b) [‘l,e,a,r,n,I,n,g,p,y,t,h,o’, ‘n’]
Explanation: The rsplit() method splits the string into a list of substrings based on the specified separator. In this case, it splits the string at the last occurrence of ‘,’ and returns two substrings: ‘l,e,a,r,n,I,n,g,p,y,t,h,o’, and ‘n’.

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

str1 = “ab bc ca ab bd ca”
temp = []

for word in str1.split():
    if word in temp:
        print(“First repeated word: “, word)
        break
    else:
        temp.append(word)

a) First repeated word: ab
b) First repeated word: bc
c) First repeated word: ca
d) No repeated words found

Correct answer is: a) First repeated word: ab
Explanation: The given string contains the word “ab” twice, and it is the first repeated word encountered in the loop. Therefore, the output will be “First repeated word: ab”.

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

string1 = “python at sqatools”
str1 = “”

for char in string1:
    if char != ” “:
        str1 += char
print(str1)

a) “pythonatsqatools”
b) “python at sqatools”
c) “python”
d) “pythonatsqatools”

Correct answer is: a) “pythonatsqatools”
Explanation: The code removes all whitespace characters from string1 and assigns the result to str1. Therefore, str1 contains the original string without any spaces.

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

string = “this is my first program”

for char in string.split(” “):
    print(char[0].upper() + char[1:-1] + char[-1].upper(), end=” “)

a) ThiS IS MY FirsT PrograM
b) This is My First Program
c) T Is M First Progra
d) t Is y firs progra

Correct answer is: a) ThiS IS MY FirsT PrograM
Explanation: The code splits the string into a list of words using the space delimiter. Then, for each word, it capitalizes the first and last characters and keeps the rest of the word unchanged. The words are printed with a space separator.

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

string = “12sqatools78”
total = 0

for char in string:
    if char.isnumeric():
        total += int(char)
print(“Sum: “, total)

a) Sum: 0
b) Sum: 18
c) Sum: 20
d) Sum: 28

Correct answer is: b) Sum: 18
Explanation: The code iterates over each character in the string. If the character is numeric, it is converted to an integer using int(char) and added to the total variable. The numbers in the string are ‘1’, ‘2’, ‘7’, and ‘8’, which sum up to 18.

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

str1 = “aabbcceffgh”
from collections import Counter
str_char = Counter(str1)

part1 = [key for (key,count) in str_char.items() if count>1]
print(“Occurring more than once: “, “”.join(part1))

a) Occurring more than once: abcf
b) Occurring more than once: abcef
c) Occurring more than once: abcefg
d) Occurring more than once: aabbcceffgh

Correct answer is: a) Occurring more than once: abcf
Explanation: The code counts the occurrences of each character in the string and stores the result in str_char. It then creates a list part1 containing only the characters that appear more than once. Finally, it prints the characters joined together. In this case, the characters ‘a’, ‘b’, ‘c’, and ‘e’ appear more than once, so the output is “Occurring more than once: abce”.

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

str1 = “@SqaTools#lin”
upper = 0
lower = 0
digit = 0
symbol = 0

for val in str1:
    if val.isupper():
        upper += 1
    elif val.islower():
        lower += 1
    elif val.isdigit():
        digit += 1
    else:
        symbol += 1

print(“Uppercase: “, upper)
print(“Lowercase: “, lower)
print(“Digits: “, digit)
print(“Special characters: “, symbol)

a) Count the occurrences of uppercase, lowercase, digits, and special characters in a given string.
b) Validate if the string only contains uppercase letters.
c) Convert the string to uppercase and count the number of uppercase letters.
d) Check if the string contains any special characters.

Correct answer is: a) Count the occurrences of uppercase, lowercase, digits, and special characters in a given string.
Explanation: The code iterates over each character in the string and checks its properties using the isupper(), islower(), and isdigit() methods. It increments the respective counters (upper, lower, digit, and symbol) based on the character’s properties. Finally, it prints the count of each category.

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

string = “sqa****too^^{ls”
unwanted = [“#”, “*”, “!”, “^”, “%”,”{“,”}”]

for char in unwanted:
    string = string.replace(char,””)
print(string)

a) sqa****too^^{ls
b) sqatools
c) sqatoolsls
d) sqatoolsls**

Correct answer is: b) sqatools
Explanation: The code removes the characters in the unwanted list from the string using the replace() method. The unwanted characters are “*”, “!”, “^”, “%”, “{“, and “}”. After removing these characters, the resulting string is “sqatools”.

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

str1 = “python 456 self learning 89”
list1 = []

for char in str1.split(” “):
    if char.isdigit():
        list1.append(int(char))
print(list1)

a) [456, 89]
b) [‘456′, ’89’]
c) [456, ’89’]
d) [‘python’, ‘self’, ‘learning’]

Correct answer is: a) [456, 89]
Explanation: The code splits the string str1 into a list of substrings using the delimiter ” “. It then iterates over each substring, checks if it consists only of digits using the isdigit() method, and if so, appends it as an integer to the list1 list. Finally, it prints the contents of list1, which will be [456, 89].

Python String MCQ : Set 3

Python String MCQ

1). What is the value of result after executing the given code?

str1 = “Sqa Tools Learning”
result = “”
vowels = [“a”,”e”,”i”,”o”,”u”,
“A”,”E”,”I”,”O”,”U”]

for char in str1:
    if char in vowels:
        result = result + char*3
    else:
        result = result + char*2
print(result)

a) Ssqqaa Ttoools Lleeaarrnniinngg
b) Sqa Tools Learning
c) SSqqaaa TToooooollss LLeeeaaarrnniiinngg
d) Sqa Tools Leaarrnniinngg

Correct answer is: c) SSqqaaa TToooooollss LLeeeaaarrnniiinngg
Explanation: The code iterates over each character in the string str1. If the character is a vowel, it appends the character three times to the result string. Otherwise, it appends the character twice to the result string. After executing the code, the result string will contain the modified string with repeated characters.

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

string = “Cricket Plays Virat”

List = string.split(” “)
List.reverse()
” “.join(List)

a) “Cricket Plays Virat”
b) “Virat Plays Cricket”
c) “Cricket Virat Plays”
d) “Plays Cricket Virat”

Correct answer is: b) “Virat Plays Cricket”
Explanation: The code snippet does not modify the variable string. It only performs operations on a list created from string.

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

string = “JAVA is the Best Programming Language in the Market”
List1 = string.split(” “)

for word in List1:
    if word == “JAVA”:
        index = List1.index(word)
        List1[index] = “PYTHON”
print(” “.join(List1))

a) “JAVA is the Best Programming Language in the Market”
b) “PYTHON is the Best Programming Language in the Market”
c) “PYTHON is the Best Programming Language in the Python”
d) “JAVA is the Best Programming Language in the Python”

Correct answer is: b) “PYTHON is the Best Programming Language in the Market”
Explanation: The code splits the string into a list of words using the space delimiter. It then iterates over the words and checks if each word is equal to “JAVA”. If it finds a match, it replaces that word with “PYTHON”. Finally, it joins the modified list of words back into a string and prints the result.

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

string = “Python efe language aakaa hellolleh”
List = string.split(” “)
new_list = []

for val in List:
    if val == val[::-1]:
        new_list.append(val)
print(new_list)

a) [‘efe’, ‘aakaa’, ‘hellolleh’]
b) [‘efe’, ‘hellolleh’]
c) [‘Python’, ‘language’]
d) []

Correct answer is: a) [‘efe’, ‘aakaa’, ‘hellolleh’]
Explanation: The code splits the string into a list of words using the space character as a delimiter. Then it checks each word in the list, and if a word is equal to its reverse (palindrome), it appends it to the new_list. Finally, it prints the new_list, which contains the palindrome words from the original string.

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

list1 = [“There”, “are”, “Many”, “Programming”, “Language”]
” “.join(list1)

a) “ThereareManyProgrammingLanguage”
b) “There are Many Programming Language”
c) “There, are, Many, Programming, Language”
d) “Many Language Programming are There”

Correct answer is: b) “There are Many Programming Language”
Explanation: The join() method concatenates the elements of list1 with spaces in between them, resulting in the string “There are Many Programming Language”. The resulting string is then printed.

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

string = “im am learning python”
count = 0

for char in string:
    count += 1
print(“Length of the string using loop logic: “, count)

a) Count the number of occurrences of each character in the string.
b) Count the number of words in the string.
c) Calculate the sum of the ASCII values of all characters in the string.
d) Calculate the length of the string.

Correct answer is: d) Calculate the length of the string.
Explanation: The code iterates over each character in the string using a loop and increments a counter variable (count) by 1 for each character. After the loop completes, the value of count represents the length of the string.

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

string1=”Prog^ra*m#ming”
test_str = ”.join(letter for letter in string1 if letter.isalnum())
print(test_str)

a) Programming
b) Program#ming
c) Program#ming
d) Error

Correct answer is: a) Programming
Explanation: The code removes all non-alphanumeric characters from the string string1 using a generator expression. The join() function concatenates the remaining alphanumeric characters into a single string. The resulting string, which contains only alphabetic and numeric characters, is then printed.

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

string2 = “Py(th)#@&on Pro$*#gram”
test_str = “”.join(letter for letter in string2 if letter.isalnum())
print(test_str)

a) Python Program
b) Pythongram
c) PythnProgram
d) Pyth@onPro#gram

Correct answer is: a) Python Program
Explanation: The code removes all non-alphanumeric characters from the string `string2` using a generator expression and the `isalnum()` method. The resulting string is then assigned to the variable `test_str` and printed, which gives the output “Python Program”.

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

string1 = “Very Good Morning, How are You”
string2 = “You are a Good student, keep it up”
List = []

for word in string1.split(” “):
    if word in string2.split(” “):
        List.append(word)
” “.join(List)

a) It counts the number of matching words between string1 and string2.
b) It concatenates the words that are common to both string1 and string2.
c) It converts the words from string1 and string2 into a list and joins them with a space.
d) It removes duplicate words from string1 and string2.

Correct answer is: b) It concatenates the words that are common to both string1 and string2.
Explanation: The code compares each word in string1 with each word in string2 and appends the common words to the List variable. Finally, it joins the words in List with a space, resulting in a string of the common words.

10). What will be the output of the code?

string = “Learning is a part of life and we strive”
print(“Longest words: “, max(string.split(” “), key=len))

a) Longest words: Learning
b) Longest words: striving
c) Longest words: Learning is
d) Longest words: part of life and

Correct answer is: a) Longest words: Learning
Explanation: The code splits the string into words and finds the longest word, which in this case is “Learning”. Therefore, the output will be “Longest words: Learning”.

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

string = “sqatoolssqatools”
string2 = string[::-1]

if string == string2:
    print(“Given string is a palindrome”)
else:
    print(“Given string is not a palindrome”)

a) Given string is a palindrome
b) Given string is not a palindrome
c) Error
d) None of the above

Correct answer is: a) Given string is a palindrome
Explanation: In this code, the string “sqatoolssqatools” is assigned to the variable string. The variable string2 is assigned the reverse of string using the slicing technique [::-1]. The condition if string == string2 checks if string is equal to its reverse. Since the reverse of “sqatoolssqatools” is the same as the original string, the condition is true and the code prints “Given string is a palindrome”.

12). What does the expression string.split(” “) do?

a) Splits the string at each space character.
b) Splits the string at each comma character.
c) Reverses the order of words in the string.
d) Joins the string with spaces.

Correct answer is: a) Splits the string at each space character.
Explanation: The split(” “) method is used to split the string into a list of substrings at each occurrence of a space character.

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

string = “sqatools python”
print(” “.join(string.split(” “)[::-1]))

a) “sqatools python”
b) “python sqatools”
c) “sqatoolspython”
d) Error

Correct answer is: b) “python sqatools”
Explanation: The code splits the string at each space using the split() method, creating a list of substrings. The [::-1] slice notation is used to reverse the order of the list. Finally, the join() method concatenates the reversed list of substrings with a space between them, resulting in “python sqatools”.

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

string = “sqatools”
dictionary = dict()

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

a) {‘s’: 1, ‘q’: 1, ‘a’: 1, ‘t’: 1, ‘o’: 2, ‘l’: 1}
b) {‘s’: 1, ‘q’: 1, ‘a’: 1, ‘t’: 1, ‘o’: 2, ‘l’: 1, ‘s’: 1}
c) {‘s’: 2, ‘q’: 1, ‘a’: 1, ‘t’: 1, ‘o’: 2, ‘l’: 1}
d) {‘s’: 1, ‘q’: 1, ‘a’: 1, ‘t’: 1, ‘o’: 1, ‘l’: 1}

Correct answer is: c) {‘s’: 2, ‘q’: 1, ‘a’: 1, ‘t’: 1, ‘o’: 2, ‘l’: 1}
Explanation: The code counts the number of occurrences of each character in the string and stores the counts in a dictionary. The resulting dictionary will have key-value pairs representing each unique character and its count in the string.

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

string = “sqatools”

for i in range(len(string)):
    if i%2 == 0:
        print(string[i], end = “”)

a) sato
b) saoo
c) saol
d) sqao

Correct answer is: c) saol
Explanation: The code iterates over the characters in the string and prints only the characters at even indices, which are ‘s’, ‘a’, ‘t’, and ‘l’.

16). What is the value of the variable count after executing the given code?

string = “python1”
count = 0

for char in string:
    if char.isnumeric():
        count += 1

a) 0
b) 1
c) 6
d) None of the above

Correct answer is: b) 1
Explanation: The code counts the number of numeric characters in the string. Since there is one numeric character ‘1’ in the string, the value of count becomes 1.

17). What will be the output of the code?

string = “I am learning python”
vowels = [“a”,”e”,”i”,”o”,”u”,”A”,”E”,”I”,”O”,”U”]
count=0

for char in string:
    if char in vowel:
        count+=1
print(“Number of vowels: “,count)

a) Number of vowels: 0
b) Number of vowels: 3
c) Number of vowels: 5
d) Number of vowels: 6

Correct answer is: d) Number of vowels: 6
Explanation: The code counts the number of vowels in the given string “I am learning python”.

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

string = “sqltools”
vowel = [“a”,”e”,”i”,”o”,”u”,”A”,”E”,”I”,”O”,”U”]
count = 0

for char in string:
    if char not in vowel:
        count += 1
print(“Number of consonants: “, count)

a) Number of consonants: 6
b) Number of consonants: 7
c) Number of consonants: 8
d) Number of consonants: 9

Correct answer is: a) Number of consonants: 6
Explanation: The code counts the number of characters in the string that are not in the vowel list, which represents the vowels. The string “sqltools” has six consonants (‘s’, ‘q’, ‘l’, ‘t’, ‘s’, ‘l’), so the output is “Number of consonants: 6”.

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

string = “sqatools”
from collections import OrderedDict
“”.join(OrderedDict.fromkeys(string))

a) “sqatools”
b) “sqatol”
c) “sqat”
d) “sqtols”

Correct answer is: b) “sqatol”
Explanation: The code removes duplicate characters from the string “sqatools” using an OrderedDict. The OrderedDict.fromkeys() method creates an OrderedDict with the unique characters from the string as keys. The “”.join() method is then used to concatenate these keys into a new string, resulting in “sqat”.

20). What will be printed as the output of the code?

string = “python$$#sqatools”
s='[@_!#$%^&*()<>?/\|}{~:]’
count=0

for char in string:
    if char in s:
        count+=1

if count > 0:
    print(“Given string has special characters”)
else:
    print(“‘Given string does not has special characters”)

a) Given string has special characters
b) Given string does not have special characters
c) Given string has 2 special characters
d) Given string does not have any special characters

Correct answer is: a) Given string has special characters
Explanation: Since the count variable is greater than 0, it indicates that the string has special characters, and thus, the corresponding message “Given string has special characters” will be printed as the output.

21). What is the output of the following code?
 
string1 = “I live in pune”
print(string1.upper())
 
a) I live in pune
b) i live IN PUNE
c) I LIVE IN PUNE
d) i live in pune
 
Correct answer is: c) I LIVE IN PUNE
Explanation: The upper() method converts all characters in the string to uppercase. In this case, it converts “i” to “I” and “pune” to “PUNE”.
 
22). What will be the output of the given code?
 
string1= “objectorientedprogramming\n”
print(string1.rstrip())
 
a) “objectorientedprogramming\n”
b) “objectorientedprogramming”
c) “objectorientedprogramming “
d) “objectorientedprogrammin”
 
Correct answer is: b) “objectorientedprogramming”
Explanation: The rstrip() method removes the newline character from the end of the string, resulting in the string “objectorientedprogramming”.
 
23). What is the value of the variable result after executing the given code?
 
a) “2.146”
b) “2.147”
c) “2.1470”
d) “2.14652”
 
Correct answer is: b) “2.147”
Explanation: The given code rounds the value of num to 3 decimal places and converts it to a string. The resulting value is then appended to the result variable. Therefore, the value of result will be “2.146” after executing the code.
 
24). What will be the output of the following code?
 
string = “five four three two one”
new_str = “”
 
for val in string.split():
    if val == “one”:
        new_str += “1”
    elif val == “two”:
        new_str += “2”
    elif val == “three”:
        new_str += “3”
    elif val == “four”:
        new_str += “4”
    elif val == “five”:
        new_str += “5”
    elif val == “six”:
        new_str += “6”
    elif val == “seven”:
        new_str += “7”
    elif val == “eight”:
        new_str += “8”
    elif val == “nine”:
        new_str += “9”
    elif val == “ten”:
        new_str += “10”
     
print(new_str)
 
a) “54321”
b) “543210”
c) “five four three two one”
d) “”
 
Correct answer is: a) “54321”
Explanation: The code iterates through each word in the string and replaces it with its corresponding numeric value. The resulting new_str will contain the concatenation of the numeric representations of the words in the original string, in the order they appear.
 
25). What is the output of the code?
 
string = “I am solving problems based on strings”
 
List = string.split(” “)
List.index(“problems”)
 
a) “problems”
b) 3
c) [“problems”]
d) Error
 
Correct answer is: b) 3
Explanation: The index() method is used to find the index of the first occurrence of the specified element in the list. In this case, “problems” is the element being searched, and its index in the list is 3.

Python String MCQ : Set 2

Python String MCQ

1). Which method is used to check if a string contains only printable characters?

a) isprintable()
b) isdisplayable()
c) isvisible()
d) isprintchar()

Correct answer is: a) isprintable()
Explanation: The isprintable() method checks if a string contains only printable characters.

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

text = “Hello World”
print(text.count(“l”))

a) 1
b) 3
c) 4
d) 9

Correct answer is: b) 3
Explanation: The count() method returns the number of occurrences of a substring in a string. In this case, “l” appears 3 times.

3). Which method is used to check if a string contains only alphanumeric characters?

a) isalphanumeric()
b) isalnum()
c) isalphanum()
d) isalphanumeric()

Correct answer is: b) isalnum()
Explanation: The isalnum() method checks if a string contains only alphanumeric characters.

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

text = “Hello World”
print(text.startswith(“Hello”))

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

Correct answer is: a) True
Explanation: The startswith() method checks if a string starts with a specific substring.

5). Which method is used to convert a string to a list of characters?

a) to_list()
b) split()
c) explode()
d) list()

Correct answer is: d) list()
Explanation: The list() function converts a string to a list of characters.

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

text = “Sqatools!”
print(text.rstrip(“!”))

a) Sqatools!
b) Sqatools
c) Sqatools!!
d) Error

Correct answer is: b) Sqatools
Explanation: The rstrip() method removes trailing occurrences of a specified character from a string.

7). Which method is used to check if a string contains only decimal characters?

a) isdecimal()
b) isdec()
c) isdigit()
d) isnumber()

Correct answer is: a) isdecimal()
Explanation: The isdecimal() method checks if a string contains only decimal characters.

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

text = “Hello World”
print(text.index(“o”))

a) 4
b) 7
c) 9
d) Error

Correct answer is: a) 4
Explanation: The index() method returns the index of the first occurrence of the specified substring in the string. In this case, “o” appears at index 4.

9). Which method is used to check if a string contains only uppercase characters?

a) isupper()
b) isuppercase()
c) isupperchar()
d) isuc()

Correct answer is: a) isupper()
Explanation: The isupper() method checks if all characters in a string are uppercase.

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

text = “Sqatools”
print(text.isalnum())

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

Correct answer is: b) False
Explanation: The isalnum() method checks if a string contains only alphanumeric characters.

11). Which method is used to check if a string contains only titlecased characters with the remaining characters being lowercase?

a) istitlecase()
b) istitle()
c) istitlelower()
d) istitlechar()

Correct answer is: b) istitle()
Explanation: The istitle() method checks if a string contains only titlecased characters with the remaining characters being lowercase.

12). Which method is used to check if a string contains only hexadecimal characters?

a) ishex()
b) ishexadecimal()
c) ishexchar()
d) isnumeric()

Correct answer is: a) ishex()
Explanation: The ishex() method checks if a string contains only hexadecimal characters.

13). Which method is used to insert a substring into a specific position in a string?

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

Correct answer is: a) insert()
Explanation: The insert() method inserts a substring into a specific position in a string.

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

string = [“i”, “am”, “learning”, “python”]
temp = 0

for word in string:
    a = len(word)
    if a > temp:
        temp = a
print(temp)

a) 2
b) 3
c) 7
d) 8

Correct answer is: d) 8
Explanation: The given code finds the length of the longest word in the list “string” and assigns it to the variable “temp”. Finally, it prints the value of “temp”, which is 8 in this case.

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

string = “sqatoolspythonspy”
sub = “spy”
print(string.count(“spy”))

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

Correct answer is: c) 2
Explanation: The count() method returns the number of occurrences of a substring within a string. In this case, “spy” appears twice in the string.

16). What is the output of the given code snippet?

letter = “aerv”

for char in letter:
    if char == “a” or char == “e” or char == “i” or char == “o” or char == “u”:
        print(f”{char} is vowel”)
    else:
        print(f”{char} is consonant”)

a) a is vowel, e is vowel, r is consonant, v is consonant
b) a is consonant, e is consonant, r is consonant, v is consonant
c) a is vowel, e is vowel, r is vowel, v is consonant
d) a is vowel, e is consonant, r is consonant, v is consonant

Correct answer is: a) a is vowel, e is vowel, r is consonant, v is consonant
Explanation: The given code snippet iterates over each character in the string “letter”. For each character, it checks if it is equal to any of the vowels ‘a’, ‘e’, ‘i’, ‘o’, or ‘u’. If it matches any of the vowels, it prints that the character is a vowel. Otherwise, it prints that the character is a consonant. In this case, ‘a’ and ‘e’ are vowels, while ‘r’ and ‘v’ are consonants.

17). Which method is used to split a string into a list of substrings?

a) split()
b) join()
c) replace()
d) find()

Correct answer is: a) split()
Explanation: The split() method is used to split a string into a list of substrings based on a specified delimiter. In this code, the delimiter is a space character.

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

string = “we are learning python”
list1 = string.split(” “)
print(“Longest word: “, max(list1, key=len))

a) Longest word: learning
b) Longest word: we
c) Longest word: python
d) Longest word: are

Correct answer is: a) Longest word: learning
Explanation: The code splits the string into individual words and finds the word with the maximum length, which in this case is “learning”. It then prints “Longest word: learning”.

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

string = “we are learning python”
list1 = string.split(” “)
print(“Smallest word: “, min(list1, key=len))

a) Smallest word: we
b) Smallest word: python
c) Smallest word: learning
d) Smallest word: are

Correct answer is: a) Smallest word: we
Explanation: The code splits the string into a list of words using space as the delimiter. The min() function is used to find the smallest word based on the length of each word. In this case, “we” has the smallest length among all the words, so it is printed as the smallest word.

20). How does the code calculate the length of the string?

string = “im am learing python”
count = 0

for char in string:
    count +=1
print(“Length of the string using loop logic: “, count)

a) It uses the built-in function len() on the string.
b) It counts the number of words in the string.
c) It iterates over each character in the string and increments a counter.
d) It calculates the sum of the ASCII values of all characters in the string.

Correct answer is: c) It iterates over each character in the string and increments a counter.
Explanation: The code uses a loop to iterate over each character in the string. For each character encountered, the counter (count) is incremented by 1. After iterating over all characters, the value of count represents the length of the string.

21). What is the value of the variable result after executing the given code?

str1 = “Programming”
result = ”

for char in str1:
    if char in result:
        result = result + “$”
    else:
        result = result + char
print(“Result :”, result)

a) Programming
b) $rogramming
c) Pro$ram$in$
d) Pro$ramming

Correct answer is: c) Pro$ram$ing
Explanation: The code iterates through each character in the string str1. If the character is already present in the result string, it appends a “$” symbol to result. Otherwise, it appends the character itself. This process results in the modified string Pro$ram$in$.

22). Which operation is performed to concatenate the substrings in the code?

a) Addition (+)
b) Subtraction (-)
c) Multiplication (*)
d) Division (/)

Correct answer is: a) Addition (+)
Explanation: The concatenation operation is performed using the addition operator (+) in Python. In the code, the substrings are concatenated by using the + operator to create the final output string.

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

string = “SqaTool”
print(string[-1]+string[1:-1]+string[0])

a) “lqaTooS”
b) “lqaToolS”
c) “lqaTools”
d) “lqaToo”

Correct answer is: a) “lqaTooS”
Explanation: In this code, string[-1] retrieves the last character ‘l’, string[1:-1] retrieves the substring ‘qaToo’, and string[0] retrieves the first character ‘S’. By concatenating these substrings in the order of last character + middle substring + first character, we get the output “lqaTooS”.

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

string =”Its Online Learning”

list1 = string.split(” “)

for word in list1:
    new_word = word[-1]+word[1:-1]+word[0]
    index = list1.index(word)
    list1[index] = new_word

” “.join(list1)

a) Its Online Learning
b) sIt enilgnO gninraeL
c) stI enlinO gearninL
d) Learning Online Its

Correct answer is: c) stI enlinO gearninL
Explanation: The given code swaps the first and last characters of each word in the string “Its Online Learning” and returns the modified string as output. The words are separated by spaces.

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

string = “We are Learning Python Codding”
list1 = string.split(” “)
vowels = [“a”,”e”,”i”,”o”,”u”]
dictionary = dict()
for word in list1:
    count = 0
    for char in word:
        if char in vowels:
            count +=1
    dictionary[word] = count
print(dictionary)

a) {‘We’: 1, ‘are’: 2, ‘Learning’: 3, ‘Python’: 1, ‘Codding’: 2}
b) {‘We’: 1, ‘are’: 1, ‘Learning’: 2, ‘Python’: 1, ‘Codding’: 2}
c) {‘We’: 0, ‘are’: 1, ‘Learning’: 1, ‘Python’: 0, ‘Codding’: 1}
d) {‘We’: 1, ‘are’: 0, ‘Learning’: 1, ‘Python’: 0, ‘Codding’: 1}

Correct answer is: a) {‘We’: 1, ‘are’: 2, ‘Learning’: 3, ‘Python’: 1, ‘Codding’: 2}
Explanation: The code splits the string into a list of words, and for each word, it counts the number of vowels. The output is a dictionary where the keys are the words and the values are the vowel counts.

Python String MCQ : Set 1

Python String MCQ

1). Which of the following methods is used to find the length of a string in Python?

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

Correct answer is: b) len()
Explanation: The len() function returns the length of a string in Python.

2). What does the “+” operator do when used with strings in Python?

a) Concatenates two strings
b) Reverses a string
c) Finds the first occurrence of a substring
d) Splits a string into a list of substrings

Correct answer is: a) Concatenates two strings
Explanation: The “+” operator concatenates two strings, joining them together.

3). Which of the following methods is used to convert a string to uppercase in Python?

a) to_lower()
b) lower()
c) upper()
d) convert_to_upper()

Correct answer is: c) upper()
Explanation: The upper() method converts a string to uppercase in Python.

4). In Python which method is used to check if a string starts with a specific substring?

a) startswith()
b) contains()
c) startswiths()
d) beginswith()

Correct answer is: a) startswith()
Explanation: The startswith() method checks if a string starts with a specific substring.

5). How can you access individual characters in a string in Python?

a) Using the [] operator with an index
b) Using the dot operator
c) Using the slice operator
d) Using the get() method

Correct answer is: a) Using the [] operator with an index
Explanation: Individual characters in a string can be accessed using the [] operator with an index.

6). Which method is used to remove leading and trailing whitespace from a string in Python?

a) trim()
b) strip()
c) remove()
d) clean()

Correct answer is: b) strip()
Explanation: The strip() method removes leading and trailing whitespace from a string in Python.

7). Which method is used to split a string into a list of substrings based on a delimiter?

a) split()
b) join()
c) separate()
d) divide()

Correct answer is: a) split()
Explanation: The split() method splits a string into a list of substrings based on a delimiter.

8). What does the “in” keyword do when used with strings in Python?

a) Checks if a string is empty
b) Checks if a string is uppercase
c) Checks if a substring is present in a string
d) Checks if a string is numeric

Correct answer is: c) Checks if a substring is present in a string
Explanation: The “in” keyword checks if a substring is present in a string in Python.

9). Which method is used to convert an integer to a string in Python?

a) int_to_string()
b) convert_to_string()
c) str()
d) to_string()

Correct answer is: c) str()
Explanation: The str() function converts an integer to a string in Python.

10). Which method is used to check if a string contains only numeric characters?

a) isdigit()
b) isnumeric()
c) isnumber()
d) isint()

Correct answer is: a) isdigit()
Explanation: The isdigit() method checks if a string contains only numeric characters.

11). Which method is used to count the occurrences of a substring in a string?
a) count()
b) find()
c) search()
d) match()

Correct answer is: a) count()
Explanation: The count() method returns the number of occurrences of a substring in a string.

12). Which method is used to check if a string ends with a specific substring?

a) endswith()
b) finishswith()
c) checkends()
d) hasending()

Correct answer is: a) endswith()
Explanation: The endswith() method checks if a string ends with a specific substring.

13). Which method is used to check if a string contains only alphabetic characters?

a) isalpha()
b) isalphabetic()
c) isletter()
d) isalphastring()

Correct answer is: a) isalpha()
Explanation: The isalpha() method checks if a string contains only alphabetic characters.

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

text = “Hello World”
print(text.capitalize())

a) Hello World
b) hello world
c) Hello world
d) Hello World

Correct answer is: d) Hello World
Explanation: The capitalize() method capitalizes the first character of a string.

15). In Python which method is used to check if a string contains only whitespace characters?

a) iswhitespace()
b) isblank()
c) isempty()
d) isspace()

Correct answer is: d) isspace()
Explanation: The isspace() method checks if a string contains only whitespace characters.

16). Which method is used to repeat a string a specified number of times?

a) repeat()
b) replicate()
c) duplicate()
d) multiply()

Correct answer is: d) multiply()
Explanation: In Python the “*” operator can be used to repeat a string a specified number of times.

17). Which method is used to check if a string contains only lowercase characters?

a) islower()
b) islowercase()
c) islowerchar()
d) islc()

Correct answer is: a) islower()
Explanation: The islower() method checks if all characters in a string are lowercase.

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

text = “Hello World”
print(text.join(“-“))

a) Hello World!
b) Hello-World!
c) H-e-l-l-o- -W-o-r-l-d
d) Error

Correct answer is: c) H-e-l-l-o-W-o-r-l-d
Explanation: The join() method joins each character of a string with a specified delimiter.

19). Which method is used to check if a string contains only titlecased characters?

a) istitlecase()
b) istitle()
c) iscapitalized()
d) istitlechar()

Correct answer is: b) istitle()
Explanation: The istitle() method checks if a string contains only titlecased characters.

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

text = “learning Python!”
print(text.title())

a) learning, python!
b) Learning Python!
c) learning Python!
d) LEARNING PYTHON!

Correct answer is: b) Learning Python!
Explanation: The title() method capitalizes the first character of each word in a string.

21). Which method is used to replace a specified number of occurrences of a substring in a string?

a) replace()
b) substitute()
c) change()
d) modify()

Correct answer is: a) replace()
Explanation: The replace() method replaces a specified number of occurrences of a substring with another substring.

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

text = “Hello World”
print(text.endswith(“d”))

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

Correct answer is: a) True
Explanation: The endswith() method checks if a string ends with a specific substring.

23). Which method is used to remove a specific character from a string?

a) remove()
b) delete()
c) strip()
d) replace()

Correct answer is: d) replace()
Explanation: The replace() method can be used to remove a specific character from a string by replacing it with an empty string.

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

text = “Hello World”
print(text.lower())

a) Hello World
b) hello world
c) Hello world
d) hello World

Correct answer is: b) hello world
Explanation: The lower() method converts all characters in a string to lowercase.

25). Which method is used to check if a string is a valid identifier in Python?

a) isidentifier()
b) isvalididentifier()
c) isname()
d) isvarname()

Correct answer is: a) isidentifier()
Explanation: The isidentifier() method checks if a string is a valid Python identifier.