What is the Difference Between Iterator and Iterable in Python

preview_player
Показать описание
In Python, an Iterator and Iterable are two related but distinct concepts.

An Iterable is any object that can be looped over with a for loop. In order to be iterable, an object must implement the iter() method, which returns an iterator object. Common examples of iterables in Python include lists, tuples, sets, and strings.

An Iterator is an object that implements the next() method, which returns the next item in the sequence. When you use a for loop to iterate over an iterable, Python automatically creates an iterator object from the iterable and calls its next() method to get each item in turn. Once there are no more items to iterate over, the iterator raises the StopIteration exception.

Here's an example that demonstrates the difference between an Iterable and an Iterator:
# Example of an Iterable
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)

In this example, my_list is an iterable object, so we can loop over it using a for loop.

# Example of an Iterator
my_iter = iter(my_list)
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))

Alternatively, we can create an iterator object using the iter() function and call its next() method repeatedly to get each item in turn.

@ParagDhawan

Рекомендации по теме
Комментарии
Автор

In iterable, you did not use the iter() method. And in iterator, you use iter() and next() methods. That's the difference.

Cloudxxx
join shbcf.ru