In Python, you can iterate over an iterable using a loop, such as a for loop, or using the next() function to get each element of the iterable one at a time. The next() function takes an iterator as an argument, and returns the next element in the iterable.
Here's an example of iterating over a list using the next() function:
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.
If you try to call next() on an iterator that has reached the end of the iterable, a StopIteration exception will be raised. 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: cherryprint(next(fruit_iterator)) # Raises StopIteration exception |
In this example, we create an iterator fruit_iterator from the fruits list using the iter() function, and then call next() four times. The first three calls to next() print each element of the list, but the fourth call raises a StopIteration exception, since there are no more elements in the list to iterate over.