Skip to content
IT Vizag
← Advanced Python Features

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

Iterators and generators

Lesson 4 of 10 · 2 min read

yield, lazy evaluation and processing huge files.

🎬 Video version coming soon — read it now

How can Python loop over a 10 GB log file on a laptop with 8 GB of memory? With iterators and generators, which produce values one at a time, only when asked.

Iterables and iterators

Anything you can loop over (a list, string, file, range) is iterable. A for loop asks it for an iterator, then keeps calling next():

🔒 Code example: sign up free (above) to unlock it.

Generators: functions that yield

A function with yield becomes a generator. Each yield hands out one value and pauses the function until the next value is requested:

🔒 Code example: sign up free (above) to unlock it.

Calling countdown(3) doesn't run anything yet. It returns a generator object that runs bit by bit as the loop asks.

Why it matters: memory

🔒 Code example: sign up free (above) to unlock it.

The generator calculates each value when needed and then forgets it.

Reading huge files lazily

🔒 Code example: sign up free (above) to unlock it.

Only one line is in memory at a time, so file size doesn't matter.

Pipelines

Generators connect like pipes, each step lazy:

🔒 Code example: sign up free (above) to unlock it.

yield from hands out every item from another iterable.

Gotchas

  • A generator can be used only once. Loop over it again and you get nothing; call the function again for a fresh one.
  • You can't use len() or indexing on a generator.
  • If you need the values several times, convert with list(), if they fit in memory.
Tip: range, zip, enumerate, map, open and dict.items() are all lazy too. That's why Python handles large data well when you keep things as iterators.

In one line

Generators yield values one at a time and pause in between, so you can process huge data with tiny memory, and chain steps into pipelines.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend