What is iteration?
Answer from AI
sobes.tech AI
Iteration in programming is the process of repeating a certain sequence of actions or traversing elements of a collection. In Python, iteration is implemented through iterators and iterable objects.
An iterable object is an object that can return an iterator. Examples include strings, lists, tuples, dictionaries, and sets.
An iterator is an object that implements the iterator protocol, having the methods __iter__ and __next__. The __iter__ method returns the iterator itself, and __next__ returns the next element in the sequence or raises the StopIteration exception when there are no more elements.
Example of iteration using a for loop:
# A list is an iterable object
my_list = [1, 2, 3, 4, 5]
# The for loop automatically works with iterators
for item in my_list:
# Each iteration prints the next element of the list
print(item)
Example of iteration using while and iterator methods (less common syntax, but demonstrates the mechanism):
my_list = [1, 2, 3, 4, 5]
# Get an iterator from the iterable object
list_iterator = iter(my_list)
# Iteration using a while loop and StopIteration
while True:
try:
# Get the next element using __next__()
item = next(list_iterator)
print(item)
except StopIteration:
# Exit the loop when elements are exhausted
break