Iterators & Generators
Take a peek under the hood of how Python uses Iterators!
StartIterables & Iterators
Lesson 1 of 2
- 1In 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 …
- 2Let’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…
- 3Now 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 _…
- 4Now 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…
- 5We 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…
- 6To 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…
- 7While 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…
- 8An 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….
- 9An 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…
- 10A 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 …
What you'll create
Portfolio projects that showcase your new skills
New Teacher in Town
In this project, you will work with several different types of iterables to create iterators to help you set up and organize the new class you’ll be teaching.
Event Coordinator
In this project, you will practice further with creating generators to retrieve and iterate through streams of data as well as using various methods to manipulate the generator data.
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory