a. run demo1() which illustrates these points. Now add one more print my_iterato
ID: 3920807 • Letter: A
Question
a. run demo1() which illustrates these points. Now add one more print my_iterator.next() at the end of demo1() and run it again. You should see a StopIteration exception.
b. Comment out all the lines: print my_iterator.next() and replace them with:
for item in my_iterator: print item
How about this? Will it also work?? for item in my_list: print item
c. Study all five demos. Demos 2, 3, 4 and 5 show that we can use a for loop to iterate through all the items in a list, a tuple, a string and a dictionary. These are all Iterable. For each of these demos, we directly placed the object under test inside the for loop to iterate through its items. The for loop kindly build an iterator for the object for us – all behind the scenes.
For example, in demo2() we stepped through the items in the list named list1as follows.
Comment out the for loop and replace it with a new for loop, which directly uses an iterator. Also print out the type of the iterator returned by iter().
Record the type of iterator returned by iter() for each demo using the exact name returned by type(my_iterator).__name__
################# Fill in this chart!!! #################
d. Here is a dictionary of function references for all five demos.
function_dictionary = {1:demo1, 2:demo2, 3:demo3, 4:demo4, 5:demo5}
# add a for loop to iterate through the function dictionary and call each function
# This should run all five demos one after the other. We iterated through the Iterable demos!
# paste your code to do that here.
Code:
Demo # Type of Iterator istiteratorExplanation / Answer
import string
import time
def demo1():
# The builtin function iter takes an iterable object and returns an iterator.
print(" DEMO1: The builtin function 'iter' takes an iterable object and returns an iterator.")
print("The type of 'iter' itself is: %s." % type(iter).__name__)
test_object = [1, 2, 3, 4] # a list is iterable
print("The test object %s has type: %s" % (repr(test_object), type(test_object).__name__))
# Now construct a listiterator for the list.
my_iterator = iter(test_object)
# my_iterator = test_object.__iter__() # an alternative and equal call
print("The method 'iter' returns an object of type: %s." % type(my_iterator).__name__)
print("The original list: ", test_object)
print("It's iterator", my_iterator)
#print my_iterator.next()
#print my_iterator.next()
#print my_iterator.next()
#print my_iterator.next()
#print my_iterator.next() to crash the program and see StopIterationException
# add one more call to next() to crash your program and see the StopIteration
# Then comment out all the above calls to next()
# and replace them with a single for loop
for item in my_iterator:
time.sleep(0.2)
print(item)
def demo2():
# Iterating over a list generated from a string after removing punctuation
print(" DEMO2: List Iteration")
einstein_quote = "Imagination is more important than knowledge. Knowledge is limited. Imagination encircles the world."
einstein_quote = einstein_quote.translate(string.punctuation)
list1 = einstein_quote.strip('.').split()
print("Our list is:", list1)
#for i in list1:
# time.sleep(0.2)
# print(i)
# Comment out the for loop and replace it with a new for loop, which directly uses an iterator.
my_iter = iter(list1)
print( "The method 'iter' returns an object of type: %s." % type(my_iter).__name__)
# Also print out the type of the iterator returned by iter().
for item in my_iter:
time.sleep(0.2)
print(item)
def demo3():
# Iterating over a tuple (immutable)
print(" DEMO3: Tuple Iteration")
tuple1 = ("Commencing countdown, engines on.", 10, 9, 8, 7, 6 , 5, 4, 3, 2, 1, 0, "Liftoff!" )
print("Our tuple is:", tuple1)
#for i in tuple1:
# time.sleep(0.2)
# print(i)
# Comment out the for loop and replace it with a new for loop, which directly uses an iterator.
my_iter = iter(tuple1)
print("The method 'iter' returns an object of type: %s." % type(my_iter).__name__)
for item in my_iter:
time.sleep(0.2)
print(item)
# Also print out the type of the iterator returned by iter().
def demo4():
# Iterating over a String
print(" DEMO4: String Iteration")
string1 = "Ectoplasm Manipulation"
print("Our string is:", string1)
#for ch in string1:
# time.sleep(0.2)
# print(ch)
my_iter = iter(string1)
print("The method 'iter' returns an object of type: %s." % type(my_iter).__name__)
# Comment out the for loop and replace it with a new for loop, which directly uses an iterator.
for item in my_iter:
time.sleep(0.2)
print(item)
# Also print out the type of the iterator returned by iter().
def demo5():
# Iterating over dictionary
print(" DEMO5: Dictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
#for i in d:
# print("%s %d" % (i, d[i]))
# Comment out the for loop and replace it with a new for loop, which directly uses an iterator.
my_iter = iter(d)
print("The method 'iter' returns an object of type: %s." % type(my_iter).__name__)
for item in my_iter:
print("%s %d"%(item,d[item]))
# Also print out the type of the iterator returned by iter().
if __name__ == "__main__":
demo1() # explore all five demos - one at a time
function_dictionary = {1:demo1, 2:demo2, 3:demo3, 4:demo4, 5:demo5}
# Let's get cute!
# Add a for loop to iterate through the function dictionary, and call each function
for item in function_dictionary:
function_dictionary[item]()
# This should run all five demos one after the other.
Table : ----------------------------->>>>>>>>>>
#Demo1 list_iterator
#Demo2 list_iterator
#DEmo3 tuple_iterator
#Demo4 str_iterator
#Demo5 dict_keyiterator
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.