Every for loop in Python uses iterators behind the scenes. Understanding them explains why you can loop over lists, strings, files, dictionaries and range in the same way, and why some objects can be looped over only once.
Two related ideas
Iterable
Iterator
Meaning
An object you can loop over
An object that produces the values of a loop, one at a time
Has
__iter__(), which returns an iterator
__next__(), which returns the next value, and __iter__(), which returns itself
Examples
list, tuple, str, dict, set, range, files
The result of iter(list), map(...), filter(...), zip(...), files, generators
Can be looped over again
Yes (each loop gets a fresh iterator)
No: once used up, it stays empty
iter(x) calls x.__iter__() and next(it) calls it.__next__().
What a for loop really does
for item in numbers: print(item) is equivalent to
it = iter(numbers) # get an iterator from the iterablewhile True: try: item = next(it) # ask for the next value except StopIteration: # no more values break print(item)
Writing your own iterator
A class becomes an iterator by defining __iter__ (returning self) and __next__ (returning the next value or raising StopIteration).
Key takeaways
Iterable: has __iter__; can be looped over many times.
Iterator: has __next__ and __iter__ (returning itself); used up after one pass.
for loops call iter() once, then next() until StopIteration.
map, filter, zip, files and generators are iterators.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Explain step by step how for x in [10, 20]: print(x) is executed in terms of iterators.
Show worked answer
First Python calls iter([10, 20]), which returns a list iterator. It then calls next() on that iterator, which returns 10; this is assigned to x and the body prints 10. It calls next() again, which returns 20, and prints it. The third next() call raises StopIteration; the for loop catches this exception silently and ends.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/python-advanced-concepts/iterables-and-iterators/ to read this page.