Iterables & Iterators
Lesson 1 of 2
  1. 1
    In Python, an iterable is an object that is capable of being looped through one element at a time. We commonly use iterables to perform the process of iteration and it is the backbone for how we …
  2. 2
    Let’s return to our for loop from before: for food_brand in dog_foods: print(food_brand + “ has “ + str(dog_foods[food_brand]) + “ bags”) Under the hood, the first step that the for loop ha…
  3. 3
    Now that we have our iterator object, how does our for loop know which value to retrieve on each iteration? Well, in addition to implementing the iter() method, iterator objects also implement…
  4. 4
    Now that we understand how iterators work under the hood, we have all the pieces to put the big picture together. Let’s look back at the following dog_foods dictionary and the for loop that perform…
  5. 5
    We have seen that the methods iter() and next() must be implemented in order for an object to be an iterator object. The implementation of these methods is known as the iterator protocol….
  6. 6
    To fully implement the iterator protocol, and be able to iterate over a custom class, we must define the iter() and next() methods. In most cases the two methods can do the following: - Th…
  7. 7
    While building our own custom iterator classes can be useful, Python offers a convenient, built-in module named itertools that provides the ability to create complex iterator manipulations. These…
  8. 8
    An infinite iterator will repeat an infinite number of times with no endpoint and no StopIteration exception raised. Infinite iterators are useful when we have unbounded streams of data to process….
  9. 9
    A finite iterator will terminate based on the length of the shortest input sequence. Finite iterators are great for sequences that we need to have terminated to prevent infinite loops or memory lea…
  10. 10
    A combinatoric iterator will perform a set of statistical or mathematical operations on an input iterable. A useful itertool that is a combinatoric iterator is the combinations() itertool. This it…
  11. 11
    Good job! In this lesson, we covered: * What an iterable is * What an iterator is * How to use built-in functions iter() and next() * How for loops use iterators * How to write custom iterators * H…

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo