Lists as Iterators

Recall the for loop introduced in the previous lab. Unlike the for loop in Snap!, Python requires an iterable. An iterable is an object which can be easily turned into a special list called an iterator. An iterator is a list of numbers used by the index variable i. This index will take on each value of the iterable (list) in sequence.


for i in range(0,5):
    print(i)
                    

Python lists are also iterables and thus can be used as iterators by a for loop! This allows the index variable to take on any desired values, numerical or otherwise!


>>> names = ["Larry", "Curly", "Moe"]
>>> for item in names:
...	    print("Hello, " + item)
Hello Larry
Hello Curly
Hello Moe
                    

Many data types in Python are iterables. Including strings!


>>> chant = "Go Bears!"
>>> for letter in chant:
...     print(letter)
G
O

B
E
A
R
S
!