Junior
What is an iterator?
sobes.tech AI
Answer from AI
An iterator in Python is an object that implements the iterator protocol. The iterator protocol requires two methods: __iter__() and __next__().
- The
__iter__()method should return the iterator object itself. - The
__next__()method should return the next element in the sequence. If there are no more elements, it should raise aStopIterationexception.
Iterators allow you to traverse elements of a collection or sequence sequentially without loading all elements into memory at once. This is especially useful when working with large amounts of data.
Examples of usage:
# Creating a list
my_list = [1, 2, 3]
# Getting an iterator from the list
my_iterator = iter(my_list)
# Using the __next__() method to get elements sequentially
print(next(my_iterator)) # Outputs 1
print(next(my_iterator)) # Outputs 2
print(next(my_iterator)) # Outputs 3
# Attempting to get the next element will raise StopIteration
# print(next(my_iterator))
A for loop in Python automatically works with iterators. When you write for item in iterable:, Python first calls iter(iterable) to get an iterator, and then repeatedly calls next() on this iterator until it receives a StopIteration.
# The for loop uses iterators
for item in my_list:
print(item)