In Python, an iterable is any object that can return its elements one at a time. Examples of iterables include lists, tuples, strings, and dictionaries. An iterable can be iterated over using a loop, such as a for loop, or using the iter() function.
An iterator, on the other hand, is an object that produces a stream of values, one at a time, using the next() function. An iterator is an object that has a __next__() method, which returns the next value in the stream, and a __iter__() method, which returns the iterator object itself. Iterators are used to efficiently process large datasets, as they can produce values on demand, rather than generating them all at once.
To create an iterator from an iterable, you can use the iter() function. The iter() function takes an iterable as an argument and returns an iterator object. Here's an example:
fruits = ["apple", "banana", "cherry"]fruit_iterator = iter(fruits) |
In this example, we create an iterator fruit_iterator from the fruits list using the iter() function.
To get the next value from an iterator, you can use the next() function. The next() function takes an iterator as an argument and returns the next value in the stream. Here's an example:
fruits = ["apple", "banana", "cherry"]fruit_iterator = iter(fruits)print(next(fruit_iterator)) # Output: appleprint(next(fruit_iterator)) # Output: bananaprint(next(fruit_iterator)) # Output: cherry |
In this example, we create an iterator fruit_iterator from the fruits list using the iter() function, and then use the next() function to print each element of the list on a separate line.
I hope this helps clarify the difference between iterables and iterators!