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.

Python List MCQ : Set 4

Python List MCQ

1). Which method can be used as an alternative to the min() function to find the minimum value from a list?

a) sort()
b) reverse()
c) pop()
d) append()

Correct answer is: a) sort()
Explanation: The sort() method can be used to sort the list in ascending order, and then the first element will be the minimum value.

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

my_list = [1, 2, 3, 4, 5]
del my_list[2]
print(my_list)

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

Correct answer is: b) [1, 2, 4, 5]
Explanation: The del keyword is used to delete an element from a list by its index. In this case, del my_list[2] removes the element at index 2 (which is 3) from my_list. The resulting list is [1, 2, 4, 5].

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

string = “i am learning python”
list1 = string.split(” “)
print(list1)

a) [“i”, “am”, “learning”, “python”]
b) [“i am learning python”]
c) [“i”, “am”, “learning”, “p”, “y”, “t”, “h”, “o”, “n”]
d) [“i”, “,”, “am”, “,”, “learning”, “,”, “python”]

Correct answer is: a) [“i”, “am”, “learning”, “python”]
Explanation: The split(” “) method splits the string at each occurrence of a space, resulting in a list of words.

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

list1 = [“Hello”, 45, “sqa”, 23, 5, “Tools”, 20]
count = 0

for value in list1:
    if isinstance(value, int):
        count += 1
print(“Total number of integers: “, count)

a) Total number of integers: 4
b) Total number of integers: 3
c) Total number of integers: 5
d) Total number of integers: 2

Correct answer is: a) Total number of integers: 4
Explanation: The code iterates over each element in `list1` and checks if the element is an instance of the `int` type using the `isinstance()` function. If it is an integer, the `count` variable is incremented. The final value of `count` is printed, which represents the total number of integers in the list. In this case, the integers in the list are 45, 23, 5, and 20, resulting in a count of 4.

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

list1 = [2, 3, 4, 7, 8, 1, 5, 6, 2, 1, 8, 2]
index_list = [0, 3, 5, 6]
new_list = []

for value in index_list:
    new_list.append(list1[value])
print(new_list)

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

Correct answer is: a) [2, 7, 1, 5]
Explanation: The code iterates through each value in the `index_list` and appends the corresponding element from `list1` to `new_list`.
– For `value = 0`, the element at index 0 in `list1` is 2, so 2 is appended to `new_list`.
– For `value = 3`, the element at index 3 in `list1` is 7, so 7 is appended to `new_list`.
– For `value = 5`, the element at index 5 in `list1` is 1, so 1 is appended to `new_list`.
– For `value = 6`, the element at index 6 in `list1` is 5, so 5 is appended to `new_list`.
Therefore, the resulting `new_list` is `[2, 7, 1, 5]`.

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

list1 = [{“name”: “john”}, {“city”: “mumbai”}, {“Python”: “laguage”}, {“name”: “john”}]
list2 = []

for i in range(len(list1)):
    if list1[i] not in list1[i+1:]:
        list2.append(list1[i])
print(list2)

a) `[{‘city’: ‘mumbai’}, {‘Python’: ‘laguage’}, {‘name’: ‘john’}]`
b) `[{“name”: “john”}, {“Python”: “laguage”}]`
c) `[{“name”: “john”}]`
d) `[]`

Correct answer is: a) `[{‘city’: ‘mumbai’}, {‘Python’: ‘laguage’}, {‘name’: ‘john’}]`
Explanation: The code iterates over each element in `list1` using the `for` loop. The condition `if list1[i] not in list1[i+1:]` checks if the current element is not repeated in the remaining elements of `list1`. If it is not repeated, the element is appended to `list2`.

7). What is the purpose of the join() method in the Python list?

a) It joins the elements of the list into a single string.
b) It counts the number of occurrences of a specified element in the list.
c) It reverses the order of the elements in the list.
d) It converts the string into a list.

Correct answer is: a) It joins the elements of the list into a single string.
Explanation: The join() method is used to concatenate the elements of the list into a single string.

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

list1 = [“a”, “b”, “c”, “d”, “e”]
list2 = [234, 123, 456, 343, 223]

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

a) {‘a’: 234, ‘b’: 123, ‘c’: 456, ‘d’: 343, ‘e’: 223}
b) {‘a’: 123, ‘b’: 234, ‘c’: 343, ‘d’: 456, ‘e’: 223}
c) {234: ‘a’, 123: ‘b’, 456: ‘c’, 343: ‘d’, 223: ‘e’}
d) {1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’, 5: ‘e’}

Correct answer is: a) {‘a’: 234, ‘b’: 123, ‘c’: 456, ‘d’: 343, ‘e’: 223}
Explanation: The zip() function is used to combine the elements of list1 and list2 into pairs. The dict() function then converts these pairs into a dictionary where elements from list1 serve as keys and elements from list2 serve as values. The resulting dictionary is printed, which will be {‘a’: 234, ‘b’: 123, ‘c’: 456, ‘d’: 343, ‘e’: 223}.

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

list1 = [2, 5, 7, 8, 2, 3, 4, 12, 5, 6]
list2 = list(set(list1))

print(list2)

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

Correct answer is: c) [2, 5, 7, 8, 3, 4, 6, 12]
Explanation: In the code, `list1` contains duplicate elements. The `set()` function is used to convert `list1` into a set, which automatically removes duplicate elements. Then, `list()` is used to convert the set back into a list. The resulting `list2` will contain unique elements from `list1` in an arbitrary order. Therefore, the output is `[2, 5, 7, 8, 3, 4, 6, 12]`.

10). Which function is used to find the maximum value from a list?

a) min()
b) max()
c) sum()
d) len()

Correct answer is: B) max()
Explanation: The max() function is used to find the maximum value from a list. When called with a list as an argument, it returns the largest value present in that list.

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

list1 = [4, 6, 8, 2, 3, 5]
list1.insert(3, [5, 2, 6])
print(list1)

a) [4, 6, 8, [5, 2, 6], 2, 3, 5]
b) [4, 6, 8, 5, 2, 6, 2, 3, 5]
c) [4, 6, 8, [5, 2, 6], [5, 2, 6], 2, 3, 5]
d) Error: ‘list’ object cannot be inserted into another list

Correct answer is: a) [4, 6, 8, [5, 2, 6], 2, 3, 5]
Explanation: The `insert()` method is used to insert an element into a list at a specified index. In this case, the list `[5, 2, 6]` is inserted at index 3 of `list1`. The resulting list will be `[4, 6, 8, [5, 2, 6], 2, 3, 5]`, where the sublist `[5, 2, 6]` is treated as a single element in `list1`.

12). What is the output of the following code?
list1 = [[“apple”, 30], [“mango”, 50], [“banana”, 20], [“lichi”, 50]]
list2 = [[“apple”, 2],[“mango”,10]]

for value in list1:
    for var in list2:
        if value[0] == var[0]:
            print(“Fruit: “, value[0])
            print(“Bill: “, value[1]*var[1])

a) Fruit: apple
Bill: 60
Fruit: mango
Bill: 500
b) Fruit: apple
Bill: 600
Fruit: mango
Bill: 500
c) Fruit: apple
Bill: 120
Fruit: mango
Bill: 500
d) Fruit: apple
Bill: 60
Fruit: mango
Bill: 50

Correct answer is: a) Fruit: apple
Bill: 60
Fruit: mango
Bill: 500

Explanation: The code iterates over the elements of list1 and list2. When it finds a match between the fruits in both lists (apple and mango), it prints the fruit name and the multiplication of their respective quantities. In this case, “apple” has a quantity of 2 in list2 and a price of 30 in list1, resulting in a bill of 60. Similarly, “mango” has a quantity of 10 in list2 and a price of 50 in list1, resulting in a bill of 500.

13). What is the output of the following code?
list1 = [80, 50, 70, 90, 95]
print(“Percentage: “, (sum(list1)/500)*100)

a) Percentage: 75.0
b) Percentage: 85.0
c) Percentage: 90.0
d) Percentage: 95.0

Correct answer is: b) Percentage: 85.0
Explanation: The code calculates the average of the values in list1 by summing them up and dividing by 500, and then multiplying by 100 to get the percentage. The sum of [80, 50, 70, 90, 95] is 385, and (385/500)*100 equals 77.0.

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

list1 = [“data”, “python”, “oko”, “test”, “ete”]
list2 = []

for value in list1:
    new = value[::-1]
    if new == value:
        list2.append(value)
print(list2)

a) [“oko”, “ete”]
b) [“data”, “python”, “test”]
c) [“oko”, “test”]
d) [“data”, “python”, “oko”, “test”, “ete”]

Correct answer is: a) [“oko”, “ete”]
Explanation: The code checks each element in `list1` and appends it to `list2` if it is a palindrome (reads the same forwards and backward). In this case, “oko” and “ete” are palindromes, so they are added to `list2`, resulting in `list2` containing [“oko”, “ete”].

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

list1 = [0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]
list2 = []

for value in list1:
    if type(value) is list:
        for var in value:
            list2.append(var)
    else:
        list2.append(value)
print(list2)

a) [0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]
b) [0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]
c) [0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122], 22, 32, 62, 72, 82, 92, 102, 112, 122]
d) [0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122], [22, 32], [62, 72, 82], [92, 102, 112, 122]]

Correct answer is: b) [0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]
Explanation: The code iterates through each element in `list1`. If an element is of type list, it iterates through its sub-elements and appends them to `list2`. If an element is not a list, it directly appends it to `list2`. The final output is the flattened list with all the sub-elements combined.

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

list1 = [(3, 5), (6, 8), (8, 11), (12, 14), (17, 23)]
list2 = []

for value in list1:
    if type(value) is tuple:
        list3 = []
        for var in value:
            list3.append(var)
        list2.append(list3)
print(list2)

a) [[3, 5], [6, 8], [8, 11], [12, 14], [17, 23]]
b) [(3, 5), (6, 8), (8, 11), (12, 14), (17, 23)]
c) [[(3, 5)], [(6, 8)], [(8, 11)], [(12, 14)], [(17, 23)]]
d) [(3, 5), 6, 8, 8, 11, 12, 14, 17, 23]

Correct answer is: a) [[3, 5], [6, 8], [8, 11], [12, 14], [17, 23]]
Explanation: The code iterates over each value in list1. If the value is a tuple, it creates a new list (list3) and appends each element of the tuple to list3. Finally, list3 is appended to list2. The output is a list of lists, where each tuple in list1 is converted to a list.

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

list1 = [[“a”, 5], [“b”, 8], [“c”, 11], [“d”, 14], [“e”, 23]]

dictionary = dict(list1)
print(dictionary)

a) {“a”: 5, “b”: 8, “c”: 11, “d”: 14, “e”: 23}
b) {“a”: [5], “b”: [8], “c”: [11], “d”: [14], “e”: [23]}
c) {“a”: [“a”, 5], “b”: [“b”, 8], “c”: [“c”, 11], “d”: [“d”, 14], “e”: [“e”, 23]}
d) Error: Invalid syntax

Correct answer is: a) {“a”: 5, “b”: 8, “c”: 11, “d”: 14, “e”: 23}
Explanation: The code converts the list of lists, `list1`, into a dictionary using the `dict()` function. Each inner list in `list1` represents a key-value pair in the dictionary. The resulting dictionary contains the keys from the first elements of each inner list and the corresponding values from the second elements of each inner list. Thus, the output is `{“a”: 5, “b”: 8, “c”: 11, “d”: 14, “e”: 23}`.

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

list1 = [“Hello”, “student”, “are”, “learning”, “Python”, “Its”, “Python”, “Language”]
for i in range(len(list1)):
    if list1[i] == “Python”:
        list1[i] = “Java”

print(list1)

a) [“Hello”, “student”, “are”, “learning”, “Java”, “Its”, “Java”, “Language”]
b) [“Hello”, “student”, “are”, “learning”, “Python”, “Its”, “Python”, “Language”]
c) [“Hello”, “student”, “are”, “learning”, “Java”, “Its”, “Python”, “Language”]
d) [“Hello”, “student”, “are”, “learning”, “Java”, “Its”, “Java”, “Language”]

Correct answer is: a) [“Hello”, “student”, “are”, “learning”, “Java”, “Its”, “Java”, “Language”]
Explanation: The code iterates over each element in the list using the range(len(list1)) construct. If an element is equal to “Python”, it is replaced with “Java”. After the loop, the modified list is printed, which will have “Python” replaced with “Java” at two positions.

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

list1 = [“Hello”, “student”, “are”, “learning”, “Python”, “Its”, “Python”, “Language”]
dictionary = dict()
list2 = []

for value in list1:
    dictionary[value] = len(value)
list2.append(dictionary)

print(list2)

a) [{‘Hello’: 5, ‘student’: 7, ‘are’: 3, ‘learning’: 8, ‘Python’: 6, ‘Its’: 3, ‘Language’: 8}]
b) [{‘Hello’: 5, ‘student’: 7, ‘are’: 3, ‘learning’: 8, ‘Python’: 6, ‘Its’: 3, ‘Python’: 6, ‘Language’: 8}]
c) [{‘Hello’: 5}, {‘student’: 7}, {‘are’: 3}, {‘learning’: 8}, {‘Python’: 6}, {‘Its’: 3}, {‘Python’: 6}, {‘Language’: 8}]
d) [{‘Hello’: 5, ‘student’: 7, ‘are’: 3, ‘learning’: 8, ‘Python’: 6, ‘Its’: 3}, {‘Python’: 6, ‘Language’: 8}]

Correct answer is: a) [{‘Hello’: 5, ‘student’: 7, ‘are’: 3, ‘learning’: 8, ‘Python’: 6, ‘Its’: 3, ‘Language’: 8}]
Explanation: The code creates a dictionary called `dictionary` and a list called `list2`. It then iterates through each value in `list1` and assigns the length of the value as the value in the `dictionary` with the value itself as the key. Finally, the `dictionary` is appended to `list2`. The output will be a list containing a single dictionary with key-value pairs mapping each word from `list1` to its corresponding length.

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

list1 = [2, 5, 7, 9, 3, 4]
print(“Remove 1 element from left”, list1[1:])

a) Remove 1 element from left [5, 7, 9, 3, 4]
b) Remove 1 element from left [2, 5, 7, 9, 3]
c) Remove 1 element from left [2, 5, 7, 9, 3, 4]
d) Remove 1 element from left [5, 7, 9, 3, 4, 2]

Correct answer is: a) Remove 1 element from left [5, 7, 9, 3, 4]
Explanation: `list1[1:]` returns a new list starting from the second element (index 1) of `list1`. The output will be [5, 7, 9, 3, 4], as the first element 2 is removed from the left side of the list.

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

list1 = []
num1 = 0
num2 = 1

for i in range(1, 10):
    list1.append(num1)
    n2 = num1 + num2
    num1 = num2
    num2 = n2

print(list1)

a) [0, 1, 1, 2, 3, 5, 8, 13, 21]
b) [1, 1, 2, 3, 5, 8, 13, 21, 34]
c) [0, 1, 2, 3, 4, 5, 6, 7, 8]
d) [0, 0, 1, 1, 2, 3, 5, 8, 13]

Correct answer is: a) [0, 1, 1, 2, 3, 5, 8, 13, 21]
Explanation: The code snippet initializes an empty list `list1` and two variables `num1` and `num2` to 0 and 1, respectively. It then enters a loop where it appends the value of `num1` to `list1` and updates `num1` and `num2` according to the Fibonacci sequence. The loop runs 9 times, resulting in the Fibonacci numbers [0, 1, 1, 2, 3, 5, 8, 13, 21]. Finally, the `list1` is printed, displaying the Fibonacci sequence.

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

list1 = [“python”, “is”, “a”, “best”, “language”, “python”, “best”]
list2 = []

for words in list1:
    if words not in list2:
        list2.append(words)
print(list2)

a) [“python”, “is”, “a”, “best”, “language”]
b) [“python”, “is”, “a”, “best”, “language”, “python”]
c) [“python”, “is”, “a”, “best”, “language”, “python”, “best”]
d) [“is”, “a”, “language”]

Correct answer is: a) [“python”, “is”, “a”, “best”, “language”]
Explanation: The code iterates over each word in list1 and checks if it exists in list2. If it doesn’t exist, it appends the word to list2. Since “python” and “best” already exist in list2, they are not appended again. Therefore, the final output is [“python”, “is”, “a”, “best”, “language”].

23). What is the output of the following code?
list1 = [(2, 3), (4, 6), (5, 1), (2, 3), (7, 9), (5, 1)]
list2 = []

for value in list1:
    if value not in list2:
        list2.append(value)
print(list2)

a) []
b) [(2, 3), (4, 6), (5, 1), (7, 9)]
c) [(2, 3), (4, 6), (5, 1), (2, 3), (7, 9), (5, 1)]
d) Error: list index out of range

Correct answer is: b) [(2, 3), (4, 6), (5, 1), (7, 9)]
Explanation: The code iterates over the elements in list1 and checks if each element is already present in list2. If not, it appends the element to list2. However, since list2 starts as an empty list and the loop does not execute, list2 remains empty. Therefore, the output is [(2, 3), (4, 6), (5, 1), (7, 9)].

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

list1 = [[1, 2], [3, 5], [1, 2], [6, 7]]
list2 = []

for value in list1:
    if value not in list2:
        list2.append(value)
print(list2)

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

Correct answer is: b) [[1, 2], [3, 5], [6, 7]]
Explanation: The code iterates over each element in `list1` and checks if the element is already present in `list2`. Since the sublists `[1, 2]`, `[3, 5]`, and `[6, 7]` are not present in `list2`, they are appended to it. Thus, `list2` contains all unique elements from `list1`.

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

list1 = [[3, 5, 6], [2, 1, 3], [5, 1, 1], [1, 2, 1], [0, 4, 1]]
print(sorted(list1, key=max))

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

Correct answer is: c) [[1, 2, 1], [2, 1, 3], [0, 4, 1], [5, 1, 1], [3, 5, 6]]
Explanation: The `sorted()` function is used to sort the elements of `list1` based on the maximum value within each sublist. The `key=max` argument specifies that the maximum value of each sublist should be used as the key for sorting. Therefore, the resulting list will be sorted in ascending order based on the maximum value of each sublist. In this case, the sorted list will be `[[1, 2, 1], [2, 1, 3], [0, 4, 1], [5, 1, 1], [3, 5, 6]]`.

Python List MCQ : Set 3

Python List MCQ

1). What is the output of the following code?
 
a = [22, 66, 89, 9, 44]
print(“Minimum: “, min(a))
 
a) Minimum: 9
b) Minimum: 22
c) Minimum: 44
d) Minimum: 89
 
Correct answer is: a) Minimum: 9
Explanation: The min() function returns the minimum value from the list ‘a’, which is 9 in this case.
 
2). What is the purpose of the following code?
 
a = [22, 45, 67, 12, 78]
b = [45, 12]
count = 0
for i in a:
    for j in b:
        if i == j:
            count += 1
if count == len(b):
    print(“Sublist exists”)
else:
    print(“Sublist does not exist”)
 
a) To find the common elements between lists a and b
b) To check if list b is a subset of list a
c) To concatenate lists a and b
d) To count the number of occurrences of elements in list b within list a.
 
Correct answer is: b) To check if list b is a subset of list a
Explanation: The code checks if every element in list b exists in list a. If all elements of b are found in a, the count variable will be equal to the length of b, indicating that b is a sublist or subset of a. Otherwise, it means that b is not a sublist or subset of a.
 
3). What is the output of the following code?
 
a = [“a”, “b”, “c”, “d”]
print(“$”.join(a))
 
a) “a$b$c$d”
b) “abcd”
c) [“a”, “b”, “c”, “d”]
d) Error: cannot join a list with a string delimiter
 
Correct answer is: a) “a$b$c$d”
Explanation: The `join()` method is used to concatenate the elements of a list into a single string, with the specified delimiter inserted between each element. In this case, the elements of list `a` are joined together using the delimiter “$”, resulting in the string “a$b$c$d”.
 
4). 1. What is the output of the following code?
 
a = [“Sqa”, “Tools”, “Online”, “Learning”, “Platform’”]
b = []
for i in a:
    b.append(i[::-1])
print(b)
 
a) [“aqS”, “slooT”, “enilnO”, “gninraeL”, “mocalfP”]
b) [“asqS”, “slooT”, “enilnO”, “gninraeL”, “mocalfP”]
c) [“Sqa”, “Tools”, “Online”, “Learning”, “Platform”]
d) [“aS”, “looT”, “enilgnO”, “gninraeL”, “mocalfP”]
 
Correct answer is: a) [“aqS”, “slooT”, “enilnO”, “gninraeL”, “mocalfP”]
Explanation: In the code, a loop iterates through each element of list ‘a’. The `i[::-1]` expression reverses each string in ‘a’. The reversed strings are then appended to the empty list ‘b’. Finally, ‘b’ is printed, which contains the reversed strings from ‘a’.
 
5). What is the purpose of the zip() function in the Python list?
 
a) Concatenate two lists into one.
b) Multiply corresponding elements of two lists.
c) Iterate over elements from two lists simultaneously.
d) Find the common elements between two lists.
 
Correct answer is: c) Iterate over elements from two lists simultaneously.
Explanation: The zip() function is used to combine elements from multiple lists into tuples. In the given code, it allows iterating over elements from list1 and list2 at the same time.
 
6). What is the output of the following code?
 
list1 = [3, 5, 7, 8, 9]
list2 = [1, 4, 3, 6, 2]
final=[]
for (a,b) in zip(list1,list2):
    final.append(list((a,b)))
print(final)
 
a) [[3, 1], [5, 4], [7, 3], [8, 6], [9, 2]]
b) [[1, 3], [4, 5], [3, 7], [6, 8], [2, 9]]
c) [[1, 4, 3, 6, 2]]
d) Error: ‘tuple’ object has no attribute ‘append’
 
Correct answer is: a) [[3, 1], [5, 4], [7, 3], [8, 6], [9, 2]]
Explanation: The code uses the zip() function to iterate over elements from list1 and list2 simultaneously. It creates a list of tuples where each tuple contains corresponding elements from both lists.
 
7). What is the output of the following code?
 
list1 = [{“a”:12}, {“b”: 34}, {“c”: 23}, {“d”: 11}, {“e”: 15}]
key = []
value = []
for element in list1:
    for val in element:
        key.append(val)
        value.append(element[val])
print(“Key : “, key)
print(“Value : “, value)
 
a) Key : [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]  Value : [12, 34, 23, 11, 15]
b) Key : [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]  Value : [{‘a’:12}, {‘b’: 34}, {‘c’: 23}, {‘d’: 11}, {‘e’: 15}]
c) Key : [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]  Value : [12, 34, 23, 11, 15, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
d) Key : [{‘a’:12}, {‘b’: 34}, {‘c’: 23}, {‘d’: 11}, {‘e’: 15}]  Value : [12, 34, 23, 11, 15]
  
Correct answer is: a) Key : [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]  Value : [12, 34, 23, 11, 15]
Explanation: The code iterates over the list1, extracting the keys and values from each dictionary. The keys are appended to the ‘key’ list, and the values are appended to the ‘value’ list. Finally, the code prints the contents of the ‘key’ and ‘value’ lists.
 
8). Which method can be used to split a string into a list based on a different delimiter?
 
a) split()
b) separate()
c) divide()
d) break()
 
Correct answer is: a) split()
Explanation: The split() method is used to split a string into a list based on a specified delimiter.
 
9). What is the correct way to create an empty list in Python?
 
a) list = []
b) list = ()
c) list = {}
d) list = None
 
Correct answer is: a) list = []
Explanation: To create an empty list in Python, we use square brackets [] without any elements inside.
 
10). What is the output of the following code snippet?
 
my_list = [1, 2, 3]
my_list.append(4)
print(len(my_list))
 
a) 1
b) 2
c) 3
d) 4
 
Correct answer is: d) 4
Explanation: The append() method is used to add an element to the end of a list. In this case, it adds the element 4 to my_list, increasing its length to 4.

11). Which method is used to remove an element from a list by its value?

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

Correct answer is: a) remove()
Explanation: The remove() method is used to remove the first occurrence of a specified element from a list.

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

my_list = [1, 2, 3, 4, 5]
sliced_list = my_list[1:5]
print(sliced_list)

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

Correct answer is: a) [2, 3, 4, 5]
Explanation: The slicing operation my_list[1:4] creates a new list containing elements from index 1 to index 4. Hence, the output is [2, 3, 4, 5]

13). Which method is used to find the index of the last occurrence of an element in a list?

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

Correct answer is: b) rindex()
Explanation: The rindex() method is used to find the index of the last occurrence of an element in a list. It starts searching from the end of the list and returns the index of the last match.

14). Which function is used to find the minimum value from a list?

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

Correct answer is: a) min()
Explanation: The min() function is used to find the minimum value from a list.

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

list1 = [12, 32, 33, 5, 4, 7]
list1[0] = “SQA”
list1[-1] = “TOOLS”
print(list1)

a) [12, 32, 33, 5, 4, 7]
b) [“SQA”, 32, 33, 5, 4, “TOOLS”]
c) [“SQA”, 32, 33, 5, 4, 7]
d) [12, 32, 33, 5, 4, “TOOLS”]

Correct answer is: b) [“SQA”, 32, 33, 5, 4, “TOOLS”]
Explanation: In the given code, the element at index 0 of `list1` is replaced with the string “SQA” using the assignment operator (`=`). Similarly, the element at index -1 (last index) of `list1` is replaced with the string “TOOLS”. Therefore, the resulting list is `[“SQA”, 32, 33, 5, 4, “TOOLS”]`.

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

list1 = [22, 45, 67, 11, 90, 67]
print(“Is 67 exist in list1? “, 67 in list1)

a) Is 67 exist in list1? True
b) Is 67 exist in list1? False
c) Is 67 exist in list1? Error
d) True

Correct answer is: a) Is 67 exist in list1? True
Explanation: The `in` keyword is used to check if an element exists in a list. In this case, the code checks if 67 exists in `list1`, and since it does, the output will be “Is 67 exist in list1? True”.

17). What is the output of the following code?
list1 = [1, 2, 3, 4, 5]
print([‘Sqa{0}’.format(value) for value in list1])

a) [‘Sqa1’, ‘Sqa2’, ‘Sqa3’, ‘Sqa4’, ‘Sqa5’]
b) [‘Sqa[1]’, ‘Sqa[2]’, ‘Sqa[3]’, ‘Sqa[4]’, ‘Sqa[5]’]
c) [‘Sqa{0}’.format(1), ‘Sqa{0}’.format(2), ‘Sqa{0}’.format(3), ‘Sqa{0}’.format(4), ‘Sqa{0}’.format(5)]
d) [‘Sqa0’, ‘Sqa1’, ‘Sqa2’, ‘Sqa3’, ‘Sqa4’]

Correct answer is: a) [‘Sqa1’, ‘Sqa2’, ‘Sqa3’, ‘Sqa4’, ‘Sqa5’]
Explanation: The code uses a list comprehension to iterate over each value in list1 and format it with ‘Sqa{0}’ to create a new list with formatted strings.

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

list1 = [[11, 2, 3], [4, 15, 2], [10, 11, 12], [7, 8, 19]]
print(max(list1, key=sum))

a) [11, 2, 3]
b) [4, 15, 2]
c) [10, 11, 12]
d) [7, 8, 19]

Correct answer is: d) [7, 8, 19]
Explanation: The `max()` function is used to find the maximum element in a list. In this case, `key=sum` is passed as an argument to specify that the sum of each sub-list should be used as the criterion for comparison. Since the sum of `[7, 8, 19]` is the highest among all the sub-lists, it will be returned as the output.

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

list1 = [2, 4, 6, 8, 3, 22]
list1.insert(3, 55)
print(list1)

a) [2, 4, 6, 8, 3, 22, 55]
b) [2, 4, 55, 6, 8, 3, 22]
c) [2, 4, 6, 55, 8, 3, 22]
d) [2, 4, 6, 8, 55, 3, 22]

Correct answer is: c) [2, 4, 6, 55, 8, 3, 22]
Explanation: The `insert()` method is used to insert an element at a specific position in the list. In this case, element 55 is inserted at index 3, shifting the remaining elements to the right. The resulting list becomes [2, 4, 6, 55, 8, 3, 22].

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

list1 = [“Learn”, “python”, “From”, “Sqa”, “tools”]
list2 = []
for words in list1:
    list2.append(words[0].upper() + words[1:-1] + words[-1].upper() + ” “)
print(“Uppercase: “, list2)

a) Uppercase: [“LearN”, “pythoN”, “FroM”, “SqA”, “ToolS”]
b) Uppercase: [“Learn”, “python”, “From”, “Sqa”, “tools”]
c) Uppercase: [“L”, “p”, “F”, “S”, “t”]
d) Uppercase: [“LEARN”, “PYTHON”, “FROM”, “SQA”, “TOOLS”]

Correct answer is: a) Uppercase: [“LearN”, “pythoN”, “FroM”, “SqA”, “ToolS”]
Explanation: The code capitalizes the first and last letters of each word in list1. The resulting list, list2, contains the modified words.

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

list1 = [[3, 5, 6], [2, 1, 3], [5, 1, 1], [1, 2, 1], [0, 4, 1]]
print(sorted(list1, key=sum))

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

Correct answer is: d) [[1, 2, 1], [2, 1, 3], [0, 4, 1], [3, 5, 6], [5, 1, 1]]
Explanation: The `sorted()` function is used to sort the list `list1` based on a custom key function, which is the `sum()` function in this case. The `sum()` function calculates the sum of each sublist in `list1`. Sorting the list based on the sum will result in ascending order based on the sum of each sublist’s elements.

22). If the list ‘a’ is empty, what will be the output of the given code?

a = []
print(“Minimum: “, min(a))

a) Minimum: None
b) Minimum: 0
c) Error: min() arg is an empty sequence
d) Error: ‘list’ object has no attribute ‘min’

Correct answer is: c) Error: min() arg is an empty sequence
Explanation: The min() function raises an error if it is called on an empty list.

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

list1 = [“Python”, “Sqatools”, “Practice”, “Program”, “test”, “lists”]
list2 = []

for string in list1:
    if len(string) > 7:
        list2.append(string)
print(list2)

a) [“Python”, “Sqatools”, “Practice”, “Program”]
b) [“Python”, “Sqatools”, “Practice”, “Program”, “lists”]
c) [“Python”, “Sqatools”, “Practice”, “Program”, “test”]
d) []

Correct answer is: b) [“Python”, “Sqatools”, “Practice”, “Program”, “lists”]
Explanation: The code iterates over each string in `list1`. If the length of the string is greater than 7, it is appended to `list2`. In this case, “Python”, “Sqatools”, “Practice”, “Program”, and “lists” have lengths greater than 7, so they are added to `list2`. Therefore, the output is `[“Python”, “Sqatools”, “Practice”, “Program”, “lists”]`.

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

list1 = [1, 1, 3, 4, 4, 5, 6, 7]
list2 = []
for a, b in zip(list1[:-1], list1[1:]):
    difference = b – a
    list2.append(difference)
print(list2)

a) [1, 2, 1, 0, 1, 1, 1]
b) [0, 2, 1, 0, 1, 1, 1]
c) [1, 0, 1, 0, 1, 1, 1]
d) [0, 1, 1, 1, 1, 1]

Correct answer is: c) [1, 0, 1, 0, 1, 1, 1]
Explanation: The code calculates the difference between consecutive elements in `list1` and stores them in `list2`. The differences are: 1-1=0, 3-1=2, 4-3=1, 4-4=0, 5-4=1, 6-5=1, 7-6=1, resulting in the list `[1, 0, 1, 0, 1, 1, 1]`.

25). What is the purpose of the following code snippet?
list1 = [3, 5, 7, 2, 6, 12, 3]
total = 0

for value in list1:
    total += value
print(“Average of list: “,total/len(list1))

a) It calculates the sum of all the values in the list.
b) It calculates the average of all the values in the list.
c) It finds the maximum value in the list.
d) It counts the number of occurrences of a specific value in the list.

Correct answer is: b) It calculates the average of all the values in the list.
Explanation: The code snippet iterates through each value in the list and accumulates the sum of all the values in the variable ‘total’. Then, it calculates the average by dividing the total sum by the length of the list and prints it.

Python List MCQ : Set 2

Python List MCQ

1). Which method is used to check if any element in a list satisfies a certain condition?

a) any()
b) some()
c) exists()
d) satisfy_any()

Correct answer is: a) any()
Explanation: The any() method is used to check if any element in a list satisfies a certain condition.

2). Which method is used to sort a list based on a custom key function?

a) sort()
b) arrange()
c) organize()
d) custom_sort()

Correct answer is: a) sort()
Explanation: The sort() method is used to sort a list based on a custom key function.

3). Which method is used to reverse the order of elements in a list?

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

Correct answer is: a) reverse()
Explanation: The reverse() method is used to reverse the order of elements in a list.

4). Which method is used to make a shallow copy of a list?

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

Correct answer is: a) copy()
Explanation: The copy() method is used to make a shallow copy of a list.

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

l = [2, 5, 7, 8]
for i in l:
    print(i ** 2)

a) 4, 25, 49, 64
b) 4, 10, 14, 16
c) 2, 5, 7, 8
d) 2, 25, 49, 64

Correct answer is: a) 4, 25, 49, 64
Explanation: The code iterates through each element in the list “l” and prints the square of each element.

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

a = [3, 5, 7, 1, 8]
count = 0
while count < len(a):
    print(a[count], “:”, a[count]**2)
    count += 1

a) 3: 3, 5: 5, 7: 7, 1: 1, 8: 8
b) 9, 25, 49, 1, 64
c) 3: 9, 5: 25, 7: 49, 1: 1, 8: 64
d) 3, 5, 7, 1, 8

Correct answer is: c) 3: 9, 5: 25, 7: 49, 1: 1, 8: 64
Explanation: The code iterates over the list ‘a’ and prints each element followed by its square.

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

a = [2, 5, 7, 9]
b = [6, 3, 0]
for i in a:
    b.append(i)
print(b)

a) [6, 3, 0, 2, 5, 7, 9]
b) [2, 5, 7, 9, 6, 3, 0]
c) [2, 5, 7, 9]
d) [6, 3, 0, 9, 7, 5, 2]

Correct answer is: a) [6, 3, 0, 2, 5, 7, 9]
Explanation: The code iterates over each element in list `a` and appends it to the end of list `b`. The resulting list `b` contains the elements from `b` followed by the elements from `a`.

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

list1 = [2, 5, 8, 0, 1]
count = 0
total = 0
while count < len(list1):
    total += list1[count]
    count += 1
print(total)

a) 0
b) 2
c) 16
d) 16, Error: list index out of range

Correct answer is: c) 16
Explanation: The code snippet initializes the variables `count` and `total` to 0. It then enters a while loop that iterates as long as `count` is less than the length of `list1`. Within the loop, it adds the value at index `count` in `list1` to the `total` variable and increments `count` by 1. After the loop, it prints the final value of `total`, which is the sum of all elements in `list1`. In this case, the sum is 2 + 5 + 8 + 0 + 1, which equals 16.

9). What is the output of the following code?
list1 = [3, 6, 9, 2]
product = 1
count = 0
while count < len(list1):
    product *= list1[count]
    count += 1
print(product)

a) 0
b) 1
c) 54
d) 324

Correct answer is: d) 324
Explanation: The code calculates the product of all the elements in the list1. The initial value of product is 1, and it gets multiplied with each element in the list (3 * 6 * 9 * 2), resulting in 324. The value of count starts at 0 and increments until it reaches the length of list1.

10). What happens to the original list ‘a’ after calling the sort() method?

a) The list ‘a’ is sorted in descending order.
b) The list ‘a’ remains unchanged.
c) The list ‘a’ is sorted in ascending order.
d) An error occurs because the sort() method cannot be used on the list ‘a’.

Correct answer is: c) The list ‘a’ is sorted in ascending order.
Explanation: The sort() method sorts the elements of the list ‘a’ in ascending order, modifying the original list.

11). What is the output of the following code?
a=[23,56,12,89]
a.sort()
print(“Smallest number: “, a[0])
 
a) Smallest number: 12
b) Smallest number: 23
c) Smallest number: 56
d) Smallest number: 89
 
Correct answer is: a) Smallest number: 12
Explanation: The list ‘a’ is sorted in ascending order using the sort() method, and then the smallest number, which is the first element of the sorted list, is printed.
 
12). What is the value of even list after executing the code snippet?
 
og_list=[23,11,78,90,34,55]
odd=[]
even=[]
for i in og_list:
    if i%2==0:
        even.append(i)
    else:
        odd.append(i)
print(“Even numbers: “,even)
print(“Odd numbers: “,odd)
 
a) [23, 11, 55]
b) [78, 90, 34]
c) [23, 11, 78, 90, 34, 55]
d) []
 
Correct answer is: b) [78, 90, 34]
Explanation: The even list stores the even numbers from og_list, which are 78, 90, and 34.
 
13). What is the purpose of the odd list in the code snippet?
 
og_list=[23,11,78,90,34,55]
odd=[]
even=[]
for i in og_list:
    if i%2==0:
        even.append(i)
    else:
        odd.append(i)
print(“Even numbers: “,even)
print(“Odd numbers: “,odd)
 
a) To store odd numbers from og_list
b) To store even numbers from og_list
c) To store all numbers from og_list
d) It has no purpose in the code snippet
 
Correct answer is: a) To store odd numbers from og_list
Explanation: The code snippet checks each number in og_list and appends the odd numbers to the odd list.
 
14). How does the code remove duplicate elements from list ‘a’?
 
a=[5,7,8,2,5,0,7,2]
b=[]
for i in a:
    if i not in b:
        b.append(i)
print(b)
 
a) It uses the remove() method to delete duplicate elements
b) It utilizes the pop() method to remove duplicate elements
c) It compares each element of ‘a’ with elements in ‘b’ and appends if not present
d) It employs the filter() function to filter out duplicate elements
 
Correct answer is: c) It compares each element of ‘a’ with elements in ‘b’ and appends if not present
Explanation: The code iterates through each element of ‘a’ and checks if it is already present in ‘b’. If not, it appends the element to ‘b’.
 
15). What is the output of the following code?
 
a=[5,7,8,2,5,0,7,2]
b=[]
for i in a:
    if i not in b:
        b.append(i)
print(b)
 
a) [5, 7, 8, 2, 5, 0, 7, 2]
b) [5, 7, 8, 2, 0]
c) [5, 7, 8, 2, 5, 0]
d) [5, 7, 8, 2, 0, 7]
 
Correct answer is: b) [5, 7, 8, 2, 0]
Explanation: The code removes duplicate elements from the list ‘a’ and stores the unique elements in list ‘b’.
 
16). What is the purpose of the condition ‘if i%2==0’ in the code?
 
a=[2,4,7,8,5,1,6]
for i in a:
    if i%2==0:
        print(i,”:”,i**2)
 
a) To check if ‘i’ is an even number
b) To check if ‘i’ is an odd number
c) To check if ‘i’ is divisible by 3
d) To check if ‘i’ is divisible by 5
 
Correct answer is: a) To check if ‘i’ is an even number
Explanation: The condition ‘if i%2==0’ checks if the element ‘i’ is divisible by 2, indicating it is an even number.
 
17). What is the value of `common_list` after executing the given code snippet?
 
list1 = [4, 5, 7, 9, 2, 1]
list2 = [2, 5, 8, 3, 4, 7]
common_list = []
for i in list1:
    if i in list2:
        common_list.append(i)
common_list
 
a) [2, 5, 7]
b) [4, 5, 7]
c) [2, 5, 8, 3, 4, 7]
d) []
 
Correct answer is: a) [2, 5, 7]
Explanation: The code iterates through each element in `list1`. If the element exists in `list2`, it appends it to the `common_list`. Therefore, the common elements between `list1` and `list2` are [2, 5, 7], which will be the resulting value of `common_list`.
 
18). What does the range(len(a)-1, -1, -1) expression represent in the code?
 
a=[1,2,3,4,55]
for i in range(len(a)-1,-1,-1):
    print(a[i],end=” “)
 
a) It generates a sequence of numbers from the length of list a to -1 in descending order.
b) It generates a sequence of numbers from the length of list a to 0 in descending order.
c) It generates a sequence of numbers from -1 to the length of list a in descending order.
d) It generates a sequence of numbers from -1 to 0 in descending order.
 
Correct answer is: b) It generates a sequence of numbers from the length of list a to 0 in descending order.
Explanation: The range() function is used to generate a sequence of indices starting from len(a)-1 (the last index of the list) down to 0 in reverse order.
 
19). What is the purpose of the end=” ” parameter in the print() function?
 
a) It adds a space character after each printed element.
b) It separates the printed elements by a space character.
c) It specifies the ending character for each line of output.
d) It removes any whitespace between the printed elements.
 
Correct answer is: a) It adds a space character after each printed element.
Explanation: The end=” ” parameter in the print() function ensures that a space character is added after each element is printed, resulting in the elements being separated by spaces in the output.
 
20). What does the reverse() method do in the Python list?
 
a) Reverses the order of elements in the list ‘x’
b) Sorts the elements of the list ‘x’ in ascending order
c) Removes duplicate elements from the list ‘x’
d) Inserts a new element at the end of the list ‘x’
 
Correct answer is: a) Reverses the order of elements in the list ‘x’
Explanation: The reverse() method is used to reverse the order of elements in a list.

21). Which of the following methods could be used to achieve the same result as reverse() in the Python list?

a) sort()
b) pop()
c) append()
d) None of the above

Correct answer is: a) sort()
Explanation: The sort() method could be used to sort the elements of the list in reverse order, achieving the same result as reverse(). However, it is not the most efficient way to reverse a list.


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

x = [2, 3, 7, 9, 3, 1]
print(“Original list: “, x)
x.reverse()
print(“Using reverse: “, x)

a) Original list: [2, 3, 7, 9, 3, 1]
Using reverse: [1, 3, 9, 7, 3, 2]
b) Original list: [2, 3, 7, 9, 3, 1]
Using reverse: [2, 3, 7, 9, 3, 1]
c) Original list: [2, 3, 7, 9, 3, 1]
Using reverse: [1, 2, 3, 3, 7, 9]
d) Original list: [2, 3, 7, 9, 3, 1]
Using reverse: [9, 7, 3, 1, 3, 2]

Correct answer is: a) Original list: [2, 3, 7, 9, 3, 1]
Using reverse: [1, 3, 9, 7, 3, 2]
Explanation: The code reverses the order of elements in the list ‘x’ using the reverse() method.

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

a = [3, 5, -8, 0, -20, -55]
for i in a:
if i >= 0:
    print(i, end=” “)

a) 3 5 0
b) 3 5 -8 0 -20 -55
c) 3 5
d) 3 5 -8

Correct answer is: a) 3 5 0
Explanation: The code iterates over each element in the list `a`. If the element is greater than or equal to 0, it is printed with a space as the end character. Therefore, only the positive elements (3, 5, and 0) are printed.

24). 1. What is the output of the following code?
a=[2,4,6,6,4,2]
b=a[::-1]
if a==b:
print(“List is palindrome”)
else:
print(“List is not palindrome”)

a) “List is palindrome”
b) “List is not palindrome”
c) Error: ‘==’ not supported between lists
d) Error: ‘print’ is not a valid function

Correct answer is: a) “List is palindrome”
Explanation: The given code checks if the list ‘a’ is a palindrome by reversing it and comparing it with the original list. Since they are the same, the output will be “List is palindrome”.

25). What is the value of ‘a’ after executing the following code?

a = [33, 56, 89, 12, 45]
a.pop(2)

a) [33, 56, 89, 12, 45]
b) [33, 56, 12, 45]
c) [33, 56, 12]
d) [33, 89, 12, 45]

Correct answer is: b) [33, 56, 12, 45]
Explanation: The `pop(2)` method removes and returns the element at index 2 from list ‘a’. In this case, the element 89 is removed from the list, resulting in the updated list [33, 56, 12, 45].

Python List MCQ : Set 1

Python List MCQ

1). What is a list in Python?

a) A collection of unordered elements
b) A collection of ordered elements
c) A collection of unique elements
d) A collection of numeric elements

Correct answer is: b) A collection of ordered elements
Explanation: A list in Python is an ordered collection of elements enclosed in square brackets.

2). How do you create an empty list in Python?

a) list()
b) []
c) emptylist()
d) create_list()

Correct answer is: b) []
Explanation: Using square brackets with no elements inside creates an empty list.

3). Which of the following is an invalid list declaration?

a) my_list = [1, 2, 3]
b) my_list = [“apple”, “cake”, “milk”]
c) my_list = [1, “apple”, True]
d) my_list = (1, 2, 3)

Correct answer is: d) my_list = (1, 2, 3)
Explanation: The invalid declaration is using parentheses instead of square brackets.

4). Which method is used to add an element at the end of a list?

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

Correct answer is: b) append()
Explanation: The append() method is used to add an element at the end of a list.

5). Which method is used to add multiple elements to a list?

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

Correct answer is: c) extend()
Explanation: The extend() method is used to add multiple elements to a list. Explanation: The extend() method adds the elements [6, 7, 8] to the end of the list.

6). How do you access the last element of a list?

a) list[-1]
b) list[0]
c) list[len(list) – 1]
d) list[last()]

Correct answer is: a) list[-1]
Explanation: Negative indexing allows you to access elements from the end of the list.

7). Which method is used to insert an element at a specific index in a list?

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

Correct answer is: d) insert()
Explanation: The insert() method is used to insert an element at a specific index in a list.

8). Which method is used to remove the element at a specific index from a list?

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

Correct answer is: d) del
Explanation: The del statement is used to remove the element at a specific index from a list.

9). How do you check if an element exists in a list?

a) check(element)
b) contains(element)
c) element in my_list
d) my_list.has(element)

Correct answer is: c) element in my_list
Explanation: The “in” operator checks if an element exists in a list.

10). Which method is used to get the number of occurrences of an element in a list?

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

Correct answer is: a) count()
Explanation: The count() method returns the number of occurrences of an element in a list.

11). Which method is used to sort a list in ascending order?

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

Correct answer is: a) sort()
Explanation: The sort() method is used to sort a list in ascending order.

12). Which method is used to sort a list in descending order?

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

Correct answer is: a) sort()
Explanation: The sort() method can also be used to sort a list in descending order.

13). Which method is used to reverse the order of elements in a list?

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

Correct answer is: a) reverse()
Explanation: The reverse() method is used to reverse the order of elements in a list.

14). Which method is used to make a copy of a list?

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

Correct answer is: a) copy()
Explanation: The copy() method is used to make a copy of a list.

15). Which method is used to clear all elements from a list?

a) clear()
b) remove_all()
c) delete_all()
d) reset()

Correct answer is: a) clear()
Explanation: The clear() method is used to remove all elements from a list.

16). Which operator is used to concatenate two lists?

a) +
b) &
c) |
d) %

Correct answer is: a) +
Explanation: The + operator is used to concatenate two lists.

17). Which method is used to convert a string into a list?

a) to_list()
b) convert()
c) split()
d) parse()

Correct answer is: c) split()
Explanation: The split() method is used to convert a string into a list by splitting it based on a delimiter.

18). Which method is used to convert a list into a string?

a) to_string()
b) convert()
c) join()
d) stringify()

Correct answer is: c) join()
Explanation: The join() method is used to convert a list into a string by joining the elements with a delimiter.


19). Which method is used to find the index of the first occurrence of an element in a list?

a) find()
b) locate()
c) index()
d) search()

Correct answer is: c) index()
Explanation: The index() method is used to find the index of the first occurrence of an element in a list.

20). Which method is used to remove and return the last element of a list?

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

Correct answer is: a) pop()
Explanation: The pop() method removes and returns the last element of a list.

21). Which method is used to insert an element at a specific position in a list?

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

Correct answer is: a) insert()
Explanation: The insert() method is used to insert an element at a specific position in a list.

22). Which method is used to remove the first occurrence of a specified element from a list?

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

Correct answer is: a) remove()
Explanation: The remove() method is used to remove the first occurrence of a specified element from a list.

23). Which method is used to extend a list by appending all the elements from another list?

a) extend()
b) expand()
c) concatenate()
d) attach()

Correct answer is: a) extend()
Explanation: The extend() method is used to extend a list by appending all the elements from another list.

24). Which method is used to count the number of occurrences of an element in a list?

a) count()
b) find()
c) locate()
d) search()

Correct answer is: a) count()
Explanation: The count() method is used to count the number of occurrences of an element in a list.

25). Which method is used to check if all elements in a list satisfy a certain condition?

a) all()
b) every()
c) each()
d) satisfy_all()

Correct answer is: a) all()
Explanation: The all() method is used to check if all elements in a list satisfy a certain condition.

Python Conditional Statements MCQ: Set 4

Python Conditional Statements MCQ

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

				
					num1 = 12.6
if type(num1) == float:
    print("True")
else:
    print("False")
				
			

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

Correct answer is:a) True
Explanation: The code checks if the type of `num1` is equal to `float`. Since `num1` is assigned the value `12.6`, which is a float, the condition evaluates to `True`, and “True” is printed.

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

				
					    x = 5
    if x < 3:
        print("A")
    if x < 7:
        print("B")
    elif x < 10:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) No output

Correct answer is:b) B
Explanation: The condition x < 3 is False. The condition x < 7 is True, so “B” will be printed. The elif condition is not checked because the first if condition is True.

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

				
					   str1 = 'Hello'
   str2 = str1[::-1]

   if str1 == str2:
       print("It is a palindrome string")
   else:
       print("It is not a palindrome string")
				
			

a) It is a palindrome string
b) It is not a palindrome string
c) Hello
d) olleH

Correct answer is:b) It is not a palindrome string
Explanation: The variable `str1` is assigned the string ‘Hello’. The variable `str2` is assigned the reverse of `str1`, which is ‘olleH’. Since `str1` is not equal to `str2`, the condition in the if statement is False, and the code inside the else block is executed, printing “It is not a palindrome string”.

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

				
					
   num = -45
   if num > 0:
       print("True")
   else:
       print("False")
				
			

a) True
b) False
c) The code will produce an error
d) No output

Correct answer is:b) False
Explanation: The value of `num` is -45, which is not greater than 0. Therefore, the condition `num > 0` evaluates to False, and the code will print “False”.

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

				
					char = 'c'
if char.islower():
    print("True")
else:
    print("False")
				
			

a) True
b) False
c) Error
d) No output

Correct answer is:a) True
Explanation: The `islower()` method is used to check if the given character is lowercase. In this case, the character ‘c’ is indeed lowercase, so the condition `char.islower()` evaluates to True. Therefore, the code will print “True”.

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

				
					   x = 5
   if x > 3:
       if x < 7:
           print("A")
       elif x < 10:
           print("B")
       else:
           print("C")
   else:
       print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The conditions x > 3 and x < 7 are both True, so “A” will be printed. The elif condition is not checked because the first if condition is True.

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

				
					for i in range(10, 16):
    if i != 13:
        print(i)
				
			

a) 10 11 12 13 14 15
b) 10 11 12 14 15
c) 11 12 13 14 15
d) 10 12 14

Correct answer is:b) 10 11 12 14 15
Explanation: The code uses a `for` loop to iterate over the range from 10 to 15 (inclusive). For each value of `i`, it checks if `i` is not equal to 13. If `i` is not equal to 13, it prints the value of `i`. Since the condition `i != 13` is `True` for all values except 13, the output will be 10, 11, 12, 14, and 15.

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

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

a) The given year is a leap year.
b) The given year is not a leap year.
c) Error: Invalid syntax.
d) Error: IndentationError.

Correct answer is:a) The given year is a leap year.
Explanation: In this code, the given year is 2000. The condition `(year%100 != 0 or year%400 == 0) and year%4 == 0` evaluates to `True` because 2000 is divisible by 4 and 400. Therefore, the code will print “The given year is a leap year.”

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

				
					   str1 = "Hello"
   if type(str1) == str:
       print("True")
   else:
       print("False")
				
			

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

Correct answer is:a) True
Explanation: The code checks if the type of `str1` is equal to `str`. Since `str1` is assigned a string value “Hello”, which is of type `str`, the condition is True, and “True” will be printed.

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

				
					   x = 5
   if x > 3:
       if x < 7:
           print("A")
       elif x < 10:
           print("B")
   elif x < 7:
       print("C")
   else:
       print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The condition x > 3 is True, so the nested if statement is evaluated. The condition x < 7 is True, so “A” will be printed. The elif statement is not executed.

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

				
					   num = 6
   if num % 2 == 0 and num % 3 == 0:
       print("FizzBuzz")
   elif num % 2 == 0:
       print("Fizz")
   elif num % 3 == 0:
       print("Buzz")
				
			

a) FizzBuzz
b) Fizz
c) Buzz
d) No output

Correct answer is:a) FizzBuzz
Explanation: The condition num % 2 == 0 is True because 6 is divisible by 2. The condition num % 3 == 0 is also True because 6 is divisible by 3. Since both conditions are True, the code will print “FizzBuzz”.

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

				
					month = "February"

if month == "january":
    print("Number of days: 31")
elif month == "february":
    print("Number of days: 28/29")
elif month == "march":
    print("Number of days: 31")
elif month == "april":
    print("Number of days: 30")
elif month == "may":
    print("Number of days: 31")
elif month == "june":
    print("Number of days: 30")
elif month == "july":
    print("Number of days: 31")
elif month == "august":
    print("Number of days: 31")
elif month == "september":
    print("Number of days: 30")
elif month == "october":
    print("Number of days: 31")
elif month == "november":
    print("Number of days: 30")
elif month == "december":
    print("Number of days: 31")
else:
    print("Invalid month")
				
			

a) Number of days: 28/29
b) Number of days: 30
c) Number of days: 31
d) Invalid month

Correct answer is:a) Number of days: 28/29
Explanation: In this code, the variable `month` is set to “February”. Since the value of `month` matches the string “february” in lowercase, the second `elif` condition is True. Therefore, the statement `print(“Number of days: 28/29”)` will be executed, indicating that February has 28 or 29 days in a leap year.

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

				
					s1 = 15
s2 = 15
s3 = 15

if s1 == s2 == s3:
    print("It is an equilateral triangle")
else:
    print("It is not an equilateral triangle")

				
			

a) It is an equilateral triangle
b) It is not an equilateral triangle
c) None of the above

Correct answer is:a) It is an equilateral triangle
Explanation: The code checks if all three sides of the triangle are equal using the equality comparison operator (==). Since s1, s2, and s3 are all equal to 15, the condition evaluates to True. Therefore, the statement “It is an equilateral triangle” is printed.

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

				
					month = "June"
if month == "February" or month == "March" or month == "April" or month == "May":
    print("Summer")
elif month == "June" or month == "July" or month == "August" or month == "September":
    print("Rainy")
else:
    print("Winter")
				
			

a) Summer
b) Rainy
c) Winter
d) No output

Correct answer is:b) Rainy
Explanation: The variable `month` is assigned the value “June”. Since the condition `month == “June” or month == “July” or month == “August” or month == “September”` is true, the code block under the `elif` statement will execute, and “Rainy” will be printed.

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

				
					char = 'A'
vowel = ["A","E","I","O","U","a","e","i","o","u"]

if char in vowel:
    print("True")
else:
    print("False")
				
			

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

Correct answer is:a) True
Explanation: The character ‘A’ is present in the list vowel, which contains all the uppercase and lowercase vowels. Therefore, the condition char in vowel evaluates to True, and “True” is printed.

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

				
					marks = 90

if 85 <= marks <101:
    print("Stream alloted: Science")
elif 70 <= marks < 85:
    print("Stream alloted: Commerce")
elif 35 <= marks < 70:
    print("Arts")
elif 0 < marks < 35:
    print("Stream alloted: Fail")
else:
    print("Invalid marks")
				
			

a) Stream alloted: Science
b) Stream alloted: Commerce
c) Arts
d) Invalid marks

Correct answer is: a) Stream alloted: Science
Explanation: The value of marks falls within the range of 85 to 101, satisfying the condition 85 <= marks < 101. Therefore, the code will print “Stream alloted: Science”.

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

				
					   x = 10
   if x > 5:
       if x < 15:
           print("A")
       else:
           print("B")
   elif x < 7:
       print("C")
   else:
       print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:a) A
Explanation: The condition x > 5 is True, so the nested if statement is evaluated. The condition x < 15 is True, so “A” will be printed. The elif and else statements are not executed in the code.

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

				
					num = 69
if num>0:
    if num%2 == 0:
        print("The given number is positive and even")
    else:
        print("The given number is positive and odd")
else:
    if num%2 == 0:
        print("The given number is negative and even")
    else:
        print("The given number is negative and odd")
				
			

a) The given number is positive and even
b) The given number is positive and odd
c) The given number is negative and even
d) The given number is negative and odd

Correct answer is:b) The given number is positive and odd
Explanation: The number `num` is 69, which is greater than 0. The first condition `num>0` is True. Then, we check if `num` is divisible by 2 (`num%2 == 0`). In this case, it is not divisible by 2. Therefore, the code prints “The given number is positive and odd”.

19). What is the output of the following code when `num` is initialized as -24?

				
					num = -24
if num>0:
    if num%2 == 0:
        print("The given number is positive and even")
    else:
        print("The given number is positive and odd")
else:
    if num%2 == 0:
        print("The given number is negative and even")
    else:
        print("The given number is negative and odd")
				
			

a) The given number is positive and even
b) The given number is positive and odd
c) The given number is negative and even
d) The given number is negative and odd

Correct answer is:c) The given number is negative and even
Explanation: Since `num` is assigned the value -24, it is less than 0. Therefore, the code executes the else block. The condition `num%2 == 0` is False because -24 is an even number. Hence, the output will be “The given number is negative and even”.

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

				
					num1 = 28
num2 = 13

if num1 == num2:
    print("The given numbers are equal")
else:
    print("The given numbers are not equal")
				
			

a) The given numbers are equal
b) The given numbers are not equal
c) Error: Invalid syntax
d) No output

Correct answer is:b) The given numbers are not equal
Explanation: In the code, `num1` is assigned the value 28, and `num2` is assigned the value 13. The `if` condition `num1 == num2` checks if `num1` is equal to `num2`. Since 28 is not equal to 13), the condition evaluates to False, and the `else` block is executed. Hence, the output will be “The given numbers are not equal”.

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

				
					   num = 5 + 6j
   if type(num) == complex:
       print("True")
   else:
       print("False")
				
			

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

Correct answer is:a) True
Explanation: The code checks the type of the variable `num` using the `type()` function. Since `num` is a complex number (5+6j), the condition `type(num) == complex` evaluates to True, and “True” will be printed.

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

				
					length = 5
breadth = 5

if length**2 == length*breadth:
    print("It is a square")
else:
    print("It is not a square")
				
			

a) It is a square
b) It is not a square
c) Error
d) No output

Correct answer is:a) It is a square
Explanation: In this code, the length and breadth variables are both assigned a value of 5. The if condition checks whether the square of the length is equal to the product of the length and breadth. Since 5 squared (25) is equal to 5 multiplied by 5 (25), the condition evaluates to True, and the code block inside the if statement is executed. Therefore, the message “It is a square” is printed as the output.

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

				
					num = -24
if num<0:
    print("Absolute value of the number: ",abs(num))
else:
    print("Absolute value of the number: ",num)
				
			

a) Absolute value of the number: -24
b) Absolute value of the number: 24
c) -24
d) 24

Correct answer is:b) Absolute value of the number: 24
Explanation: The code checks if the variable “num” is less than 0. Since the value of “num” is -24, which is less than 0, the if condition is True. The absolute value of -24 is 24, so the output will be “Absolute value of the number: 24”.

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

				
					   s1 = 15
   s2 = 10
   s3 = 18

   if s1 != s2 != s3:
       print("It is a scalene triangle")
   else:
       print("It is not a scalene triangle")
				
			

a) It is a scalene triangle
b) It is not a scalene triangle
c) It is a scalene triangle if s1 > s2 > s3
d) It is not a scalene triangle if s1 = s2 = s3

Correct answer is:b) It is not a scalene triangle
Explanation: In the given code, the if condition checks if s1 is not equal to s2 and s2 is not equal to s3. Since s1 = 15, s2 = 10, and s3 = 18, the condition evaluates to True. However, a scalene triangle should have all sides of different lengths. Therefore, the else statement is executed and “It is not a scalene triangle” is printed.

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

				
					num = 117
last_digit = num%10

if last_digit%4 == 0:
    print("The last digit is divisible by 4")
else:
    print("The last digit is not divisible by 4")
				
			

a) The last digit is divisible by 4
b) The last digit is not divisible by 4
c) The code will result in an error
d) No output will be printed

Correct answer is:b) The last digit is not divisible by 4
Explanation: The code checks if the last_digit is divisible by 4 using the condition last_digit%4 == 0. If the condition is True, it prints “The last digit is divisible by 4”. Otherwise, it prints “The last digit is not divisible by 4”. Since the value of last_digit is 7, which is not divisible by 4, the output will be “The last digit is not divisible by 4”.