Sobes.tech
Junior

What is an iterator?

sobes.tech AI

Answer from AI

An iterator is an object that allows sequentially traversing the elements of a collection (list, array, set, etc.) without revealing its internal structure.

It provides methods for:

  • Moving to the next element (next).
  • Checking for the presence of the next element (hasNext/__next__ and catching StopIteration in Python).

Using iterators ensures a unified way to access elements of different collection types.

Example in Python:

# Collection
my_list = [1, 2, 3]

# Getting an iterator
my_iterator = iter(my_list)

# Traversing elements with the iterator
print(next(my_iterator)) # Outputs 1
print(next(my_iterator)) # Outputs 2
print(next(my_iterator)) # Outputs 3

# Attempting to get the next element after the iterator is exhausted
# next(my_iterator) # Will raise StopIteration

Example in Java:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

// Collection
List<String> mylist = new ArrayList<>();
mylist.add("A");
mylist.add("B");
mylist.add("C");

// Getting an iterator
Iterator<String> myIterator = mylist.iterator();

// Traversing elements with the iterator
while (myIterator.hasNext()) {
    System.out.println(myIterator.next()); // Will output A, B, C in order
}