What is iterator?

An iterator is a tool that lets you go through each item in a collection (like a list, set, or dictionary) one at a time, without having to know how the collection stores those items internally.

Let's break it down

  • Collection: A group of items (e.g., [1, 2, 3] or {"a": 1, "b": 2}).
  • Iterator: An object that remembers where it is in the collection and can give you the next item when you ask for it.
  • How it works: You ask the iterator for the “next” item; it returns the item and moves its internal pointer forward. When there are no more items, it signals that it’s done.

Why does it matter?

Iterators let you handle large or infinite data sets efficiently because they only produce one item at a time, saving memory. They also give a consistent way to loop over different kinds of collections without writing special code for each type.

Where is it used?

  • Looping with for loops in languages like Python, Java, and JavaScript.
  • Reading files line‑by‑line.
  • Streaming data from the internet or a database.
  • Implementing custom data structures that need to be traversed.

Good things about it

  • Memory efficient: No need to load the whole collection at once.
  • Uniform interface: Same code works for lists, sets, dictionaries, generators, etc.
  • Lazy evaluation: Items are generated only when needed, which enables infinite sequences.
  • Composable: You can chain iterators (e.g., map → filter → reduce) to build powerful pipelines.

Not-so-good things

  • Once an iterator is exhausted, you can’t reuse it without creating a new one.
  • Debugging can be harder because the data isn’t all visible at once.
  • Some operations (like random access) are not possible; you must traverse sequentially.
  • Improper use may lead to hidden performance costs if the iterator does heavy work on each step.