Day 3 - Something about Iterators

Today was devoted to catching up on the Udemy Ultimate Python Programming exercises. The 3 sections I covered were:

All 3 sections covered a decent amount of basic material around these core constructs, and the most interesting of the 3 were the list comprehensions. However, section 9 left me a bit perplexed with respect to finding a good use case on using an ‘external’ iterator. Here’s the example:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Chapter 9, Exercise 1 """
SQUARE = ((10, 8), (10, 23), (25, 23), (25, 8))
SQUAREIT = iter(SQUARE)
print next(SQUAREIT)
print next(SQUAREIT)
print next(SQUAREIT)
print next(SQUAREIT)

In this example, the variable SQUARE is a multi-dimensional tuple that stores the 4 points of a square. The variable SQUAREIT is defined as an iterator that is explicitly tied to the data contained in the variable SQUARE . As you can see from the remaining code, I simply run the next() function ‘manually’ to iterate through all of the data contained inside the tuple. While I understand the concept, what I don’t get is why I would ever choose to define my own iterator, especially since many of the data structures that I might use in Python automatically have iteration features built-in? The only example that makes sense is if I ‘override’ the natural function of what an iterator does, i.e. iterating through every other piece of data, as opposed to serially iterating over all of them. If that’s not the point, then somebody, please explain to me, what’s the use case for creating and using your own iterator?

Dazed and Confused, Jay. (Not really…)

Jason T Clark

Jason T Clark

Father. Musician. Gamer. Coder.

comments powered by Disqus
rss facebook twitter github youtube mail spotify instagram linkedin