MCQ

Python MCQ and Answers – Part 13

This collection of Python Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer.
 

1. What is the output of the following code?
print([i.lower() for i in "HELLO"])

A hello

B [‘hello’]

C ‘hello’

D [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]  
 

D
We go through each letter of the String.
 

2. Suppose list1 = [0.5 * x for x in range(0, 4)], so list1 is:

A [0.0, 0.5, 1.0, 1.5, 2.0]

B [0.0, 0.5, 1.0, 1.5]

C [0, 1, 2, 3, 4]

D [0, 1, 2, 3]  
 

B
 

3. What methods should the “iterator” object implement?

A __iter__()

B __iter__() and __next__()

C __iter__() and __super__()

D __iter__(), __super__() and __next__()

B
Let’s take an example :

class MyClass:
   def __init__(self):
      self.language = ['Python','Java','PHP','C']
      self.i = -1

   def __iter__(self):
      return self

   def __next__(self):
      self.i += 1
      if self.i == len(self.language):
         raise StopIteration
      else:
         return self.language[self.i]

o = MyClass() #Create the object
Myiterator = iter(o) #Create the iterator

print(next(Myiterator))
print(next(Myiterator))
print(next(Myiterator))

Output:

Python
Java
PHP
C
 

4. To add a new item to a list, what function do we use?

A list1.addEnd(3)

B list1.addLast(3)

C list1.append(3)

D list1.add(3)

C
We use the append() function to add an item to the list.
 

5. What is the output of the following code?
print([if i%2==0: i; else: i+1; for i in range(4)])

A [0, 2, 2, 4]

B [1, 1, 3, 3]

C Error

D None of the above

C
Invalid syntax
 

6. What is the output of the following code?
x={}
x[2]=1
x[1]=[2,3,4]
print(x[1][1])

A 4

B 3

C [2,3,4]

D Error

B
x={1:[2,3,4],2:1}. x[1][1] refers to the second element with the key 1.
 

7. To insert 3 at the second position in list1, what instruction do we use?

A list1.insert(2, 3)

B list1.insert(1, 3)

C list1.add(2, 3)

D list1.append(2, 3)

B
 

8. Which of the following is the same as
list(map(lambda x: x**-1, [1, 2, 3]))

A [x**-1 for x in [(1, 2, 3)]]

B [1/x for x in (1, 2, 3)]

C [1/x for x in [(1, 2, 3)]]

D Error

B
x**-1 is evaluated to (x)**(-1)
 

9. To remove the string “hello” from list1, what instruction do we use?

A list1.removeOne(“hello”)

B list1.removeAll(“hello”)

C list1.remove(hello)

D list1.remove(“hello”)

D
 

10. Suppose list1 is [3, 4, 1, 20, 5], so what is the output of list1.index(1)?

A 0

B 1

C 2

D 4

C
Run help(list.index) to get more details.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *