This Quiz contains totally 10 Questions each carry 1 point for you.
1. Which of the following are iterable objects?
Lists
Strings
Sets
All of the above
Correct!
Wrong!
2. Can we use a for loop to iterate through an iterable object?
True
False
Correct!
Wrong!
3. To create an object/class as an iterator you have to implement the methods _______ and ______ to your object.
__iter__() and __next__()
__next__() and __iter__()
For loop and next()
None of the above
Correct!
Wrong!
4. What would be the output of the following program?
class yrange:
def __init__(self, n):
self.i = 0
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.i < self.n:
i = self.i
self.i += 1
return i
else:
raise StopIteration()
y = yrange(3)
print(next(y))
print(next(y))
print(next(y))
print(next(y))
code runs well and prints 0,1,2 as output
code runs well and prints nothing
code runs well and prints 0,1,2 and also raises Stopiteration error
code raises Stopiteration error
Correct!
Wrong!
5. What error is raised when there are no next element to access when next() method is called?
Stopiteration
Runtimeerror
OutofBound
None of the above
Correct!
Wrong!
6. What would be the output of the following code?
x = iter([1, 2, 3])
x
list iterator address
tuple iterator address
set iterator address
None of the above
Correct!
Wrong!
7. The next() method used in Iteration Protocol to get the values one at a time.
True
False
Correct!
Wrong!
8. What is the output of the below Python code?
class reverse_iter:
def __init__(self, n):
self.n = n
def __iter__(self):
return self
def __next__(self):
if len(self.n) > 0:
return self.n.pop()
else:
raise StopIteration()
it = reverse_iter([1, 2, 3, 4])
print(next(it))
print(next(it))
3
2
Error
None of the above
Correct!
Wrong!
9. Strings are non-iterable objects.
True
False
Correct!
Wrong!
10. What is the output of the below Python code for two more print(next(myiter)) statements?
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
StopIteration
5
4
None of the above
Correct!
Wrong!
Share the quiz to show your results !
Subscribe to see your results
Ignore & go to results
Python-Iterators-Quiz
You got %%score%% of %%total%% right
%%description%%
%%description%%
Loading...