Level 1
0 / 100 XP

Iterator and Iterable

Welcome to the lesson on iterators and iterables in Python! In this lesson, we will be discussing two important concepts that are essential for working with loops in Python.

Iterator

An iterator is an object that can be used to iterate over a collection of items, such as a list or a dictionary. In Python, an iterator must implement two methods: __iter__() and __next__(). The __iter__() method is called when the iterator is initialized, and it should return the iterator object itself. The __next__() method is called each time the iterator advances to the next item in the collection.

Iterable

On the other hand, an iterable is any object that can be iterated over. This means that it must implement the __iter__() method, which returns an iterator for the object. Some examples of iterables in Python include lists, tuples, dictionaries, and sets.

To use an iterator in Python, you first need to create an iterator object by calling the iter() function on an iterable. Then, you can use a for loop to iterate over the items in the iterator. Here's an example:

Python
# Create a list of numbers.. this is iterable numbers = [1, 2, 3, 4, 5] # Create an iterator for the iterable list above iterator = iter(numbers) # Use a for loop to iterate over the items in the iterator for number in iterator: print(number)

In this example, we create a list of numbers and then create an iterator for the list by calling iter() on the list. Then, we use a for loop to iterate over the items in the iterator and print each item to the console.

Iterators and iterables are important concepts to understand because they are essential for working with loops in Python.

When are iterators useful?

An iterator would be useful in situations where you need to process a large collection of items, but you don't want to load the entire collection into memory at once. For example, imagine that you have…