Python Random Fact: iterator vs list

iterator vs list

Here is a simple for-loop over an iterator:

nums = iter(range(5))
for n in nums:
    print(n)

And here is the same loop over a list:

nums = list(range(5))
for n in nums:
    print(n)

They print the same numbers. Do you know what is different?

memory usage difference and why

An iterator produces values one by one, so it only needs O(1) memory for the current item and a small amount of state. A list stores every item at once, so it needs O(n) memory to hold all items.

That means iter(range(10_000_000)) is cheap to create, but list(range(10_000_000)) allocates space for ten million integers. When data is large, that extra allocation can be the difference between smooth execution and a memory error.

actual usecases

  • Large files or logs: stream lines with an iterator instead of loading the whole file.
  • Data pipelines: chain generators so each step consumes one item at a time.
  • One-pass processing: if you only need to scan once, an iterator is ideal.

conclusion

If you only need to access values iteratively and the data can be large, use an iterator. Lists are great when you need random access or repeated passes, but they cost O(n) memory upfront.