What is the Difference Between Iterator and Iterable in Python

Published: 12 March 2023
on channel: Parag Dhawan
736
8

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‬

https://paragdhawan.blogspot.com/2023...


On this page of the site you can watch the video online What is the Difference Between Iterator and Iterable in Python with a duration of hours minute second in good quality, which was uploaded by the user Parag Dhawan 12 March 2023, share the link with friends and acquaintances, this video has already been watched 736 times on youtube and it was liked by 8 viewers. Enjoy your viewing!