Python: Iterables, Iterators, Generators

What’s the difference between all these?

Richard Mei
2 min readDec 28, 2020

Everyone with some basic knowledge of programming knows what is meant by iterating. For example, if we had an object with a gigantic list of random numbers, iterating through the list means to go through each value in the list. We can do this using either a for loop or a while loop like below:

list_example = [1,21,3,50,66,7,90,31,236,3400]#for loop
for element in list_example:
print(element)
#while loop
i = 0
while i < len(list_example)
print(list_example[i])
i += 1

Both of these examples are iterating through the list, but the while loop needs an index variable. Using the while loop is using recursion to iterate through the loop and this works because a list is iterable, as is a dictionary, collection, or tuple. The importance difference that I didn’t know from the beginning is the for loop creates an iterator (which is it’s own special object)and goes to the next until the end.

Iterator

By definition the iterator “is a object that contains a countable number of values”. The object itself will be called, literally, an iterator and can actually easily be made by casting like so:

my_list = [1,2,3,4]
myiter = iter(my_list)
myiter
>> <list_iterator at ___ >

Now we have an iterator, and once we call next, it will give it the next value in the iterator, so first 1, then 2, then 3. . . and once there are no more iterations, it raises a StopIteration

next(myiter)
>> 1
next(myiter)
>> 2
...
#5th next would raise>> StopIteration

But you may be asking, what’s so special about having an iterator? The reason may be having an iterator will run faster than having a giant object that you have to store, but actually an important iterator to mention is a generator.

Generator

A generator is a type of iterator, but is instantiated differently. The first way to make a generator is to use syntax that looks like a “tuple comprehension”. It’s easier to see what I mean:

my_squares_generator = (i**2 for i in [1,2,3,4])
my_squares_generator
>> <generator object at __>

Notice the parenthesis and the glaring similarities to a list comprehension. Another way to create a generator would be using a function and a yield statement.

def squares_generator(start, end):
while start < end + 1:
yield start**2
start += 1
squares_generator(1,4)

The yield statement stops the sequence until the object created is gone through, just like other iterators. The importance of this if we wanted to create a gigantic sequence of numbers, we would could make one efficiently without having a giant object taking up all the memory.

Conclusion

That’s the quick brush over iterators and generators. This was a distinction that I thought was cool, and each an iterator and generator has its own special uses.

--

--