PYTHONDATASCIENCETOOLBOX_iterators _ Python_ch_1_Iterating over iterables
PYTHONDATASCIENCETOOLBOX_iterators _ Python_ch_1_Iterating over iterables
Great, you're familiar with what iterables and iterators are! In this exercise, you will reinforce your
knowledge about these by iterating over and printing from iterables and iterators.
You are provided with a list of strings flash. You will practice iterating over the list by using
a for loop. You will also create an iterator for the list and access the values from the iterator.
Instructions
100 XP
Create a for loop to loop over flash and print the values in the list. Use person as the
loop variable.
Create an iterator for the list flash and assign the result to superhero.
Print each of the items from superhero using next() 4 times.
# Create a list of strings: flash
flash = ['jay garrick', 'barry allen', 'wally west', 'bar
t allen']
# Print each list item in flash using a for loop
SOLUTION
# Create a list of strings: flash
flash = ['jay garrick', 'barry allen', 'wally west', 'bar
t allen']
# Print each list item in flash using a for loop
for person in flash:
print(person)
# Create an iterator for flash: superhero
superhero = iter(flash)
# Print each item from the iterator
print(next(superhero))
print(next(superhero))
print(next(superhero))
print(next(superhero))
Iterating over iterables (2)
One of the things you learned about in this chapter is that not all iterables are actual lists. A
couple of examples that we looked at are strings and the use of the range() function. In this
exercise, we will focus on the range() function.
You can use range() in a for loop as if it's a list to be iterated over:
for i in range(5):
print(i)
Recall that range() doesn't actually create the list; instead, it creates a range object with an
iterator that produces the values until it reaches the limit (in the example, until the value 4).
If range() created the actual list, calling it with a value of 10100 may not work, especially since a
number as big as that may go over a regular computer's memory. The value 10100 is actually
what's called a Googol which is a 1 followed by a hundred 0s. That's a huge number!
Your task for this exercise is to show that calling range() with 10100 won't actually pre-create
the list.