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 used an iterator’s iter() method to create an iterator object, how does our for loop know which value to retrieve on each iteration? Well, the iterator object has a method called _…
  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 for an object to be an iterator object. The implementation of these methods is known as the iterator protocol. If we d…
  6. 6
    To iterate over a custom class we must implement the iterator protocol by defining the iter() and next() methods. In most cases the two methods can do the following: - The iter() metho…
  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
    An input-dependent iterator will terminate based on the length of one or more input values. They are great for working with and modifying existing iterators. A useful itertool that is an input-dep…
  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 …
  11. 11
    Good job! In this lesson, we covered: * Iterables and iterators and how they differ. * Using the iter() funtion to create an iterator. * Using the next() function to manually iterate over an iterat…

What you'll create

Portfolio projects that showcase your new skills

How you'll master it

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