Remembering Iterators and Iterables
00:00 Iterators and iterables are key concepts in Python that power the way you loop over data. An iterable is anything you can loop over, like a list or a string while an iterator is what does the work, which is returning one item at a time.
00:16 But did you know that you can actually create your own custom iterators and iterables? It’s a powerful way of controlling how your data is accessed and processed.
00:26 But before all that, let’s first refresh your memory on what these terms really mean. Let’s start with iterators. In Python, an iterator allows you to iterate over collections of data such as lists, tuples, dictionaries, and sets.
00:43 An iterator is useful for data streams that have an unknown or huge number of items.
00:52 Iterators take responsibility for two main actions, returning the data from a stream or container one item at a time, and keeping track of the current and visited items.
01:07
Time to remember what iterables are. An iterable is any Python object that can return its members one at a time, allowing it to be looped over in a for
loop.
01:20 The key difference to understand here is that an iterable is like a collection of items, while an iterator is what’s actually used to step through those items.
01:32 Let’s walk through this table to better understand the key differences between an iterator and an iterable, especially because you’ll soon be implementing your own custom iterable and iterators, so you’ll need to know which magic methods to use to make them work.
01:50
Let’s see if you can loop over an iterator and an iterable. You cannot directly use a for
loop on an iterator. You typically get an iterator from an iterable and then use it, but you can loop over an iterable, like a list or a string.
02:08
For both iterators and iterables, you need to implement the .__iter__()
magic method. The .__iter__()
method usually returns the iterator object itself.
02:19
For an iterator, you must implement the .__next__()
magic method. This method returns the next item in the sequence each time it’s called, but you don’t need to implement the .__next__()
method in an iterable.
02:32 Instead, it relies on the iterator to handle moving through the items.
02:37 An iterator cannot be reused once it’s been fully iterated over. If you want to loop over the data again, you need to create a new iterator, but an iterable can be reused for multiple passes.
02:51
Every time you start a new for
loop, it generates a fresh iterator allowing you to go through the items again. Well done. You’ve just learned the key differences between iterators and iterables and how they work together using essential magic methods.
Become a Member to join the conversation.