PNL Learn

Comprehensions and Generators

Write concise, fast, Pythonic data transformations.

Replace accumulator loops with list, dict and set comprehensions, place if correctly to filter or to choose a value, and keep side effects in loops. Then nested comprehensions that flatten data or build rows, lambdas made in a comprehension, any and all (and what they say about an empty list), enumerate, zip with strict=True and sorting by several keys. You will learn how iteration really works with iter, next and StopIteration, write generator functions and generator expressions, trace when lazy code actually runs, and dodge the one-pass trap. The course ends with itertools and lazy pipelines: a log filter, a batching generator, running balances and a top-N report by category.

IntermediatePython5 lessons73 exercisesAbout 5.5 h
Create a free account

What you will learn

  • List comprehensions
  • Filters and conditional expressions
  • Dict and set comprehensions
  • Nested comprehensions
  • any and all
  • enumerate, zip and sorted keys
  • Iterators
  • Generators and lazy evaluation
  • itertools

Lessons

  1. 1

    List Comprehensions

    Map and filter lists in one readable expression, choose a value with if and else, and know when a plain loop is the better choice.

    14 exercises

  2. 2

    Dict, Set and Nested Comprehensions

    Build lookups, invert dicts, collect unique values, flatten and build grids with nested comprehensions, and know when to stop.

    15 exercises

  3. 3

    any, all and Built-in Iteration Tools

    Answer yes or no questions about data, number and pair items safely, and sort by several keys at once.

    14 exercises

  4. 4

    Iterators and Generators

    See how for loops really work, write lazy generator functions, trace when lazy code runs, and avoid the one-pass trap.

    15 exercises

  5. 5

    itertools and Putting It Together

    Slice, chain, total and group lazy streams with itertools, trace a pipeline, then build four real data-processing tools.

    15 exercises

How you practice

You practice in the browser and every exercise gives you feedback right away. This course uses these formats:

  • Code exercise: 30
  • Predict the output: 13
  • Fix the bug: 10
  • Fill in the blank: 7
  • Multiple choice: 4
  • Type the answer: 4
  • Select all that apply: 2
  • Reorder lines: 1
  • Match the pairs: 1
  • Spot the bug: 1

Aligned to

PCEP-30-02Python InstituteSource
  • Functions and Exceptions
    • 4.1Decompose the code using functions
PCAP-31-03Python InstituteSource
  • Miscellaneous
    • 5.1Build complex lists using list comprehensions
CS2023ACM / IEEE-CS / AAAISource
  • Software Development Fundamentals
    • SDF-FundamentalsFundamental Programming Concepts and Practices

Proto Node Labs is not affiliated with or endorsed by Python Institute and ACM / IEEE-CS / AAAI. Exam names are trademarks of their owners.