Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 15 / FUNCTIONS AND REUSABLE CODE

Transform data without hiding intent

Build readable pipelines with comprehensions and generator expressions.

FoundationTutorial 10 min core+7 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 10 minutes; optional deep dive: 7 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Map and filter with comprehensions
  • Choose a loop for complex work
  • Distinguish eager and lazy results
01

Read the plain loop first

A list comprehension builds a new list by visiting inputs, optionally keeping some, and transforming each kept value.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Express a short map-and-filter rule without changing the source or burying the intent in several temporary steps.

Words you will see

Transform
Compute an output from an input, such as value * value.
Filter
Decide whether an input contributes an output.
Eager
Compute and store all results now rather than when requested later.

Read in execution order

Although the output expression appears first in [value * value for value in values if value > 0], the process visits a value, tests value > 0, then squares it if kept. -2 and 0 fail the condition; 3 and 4 produce 9 and 16.

This is the same rule as an explicit loop that appends only inside the if branch. Output order follows the source traversal. Repeated positive inputs would produce repeated squares.

Keep the condition on the intended value

Filtering value > 0 is not the same as squaring everything and then testing the square. A negative input would have a positive square, but this rule deliberately excludes the original negative.

The new list does not mutate values. An empty source or no matches produces []. For n inputs and k kept values, ordinary numeric work is O(n) and the new list uses O(k) references. Use a loop when the rule grows into many actions or branches.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. values = [-2, 0, 3, 4]

    Include negative, zero and positive boundary cases.

  2. squares = [value * value for value in values if value > 0]

    Keep 3 and 4 before squaring them to get 9 and 16.

  3. print(values)

    Show that the original values and order remain unchanged.

A comprehension builds a new collection from an iterable. Read [transform(x) for x in source if keep(x)] as select each x, keep matching ones, then transform. A normal loop is better when you need several side effects or complex branching.

Conceptual filter-then-transform flow for the original values, not live tracing of edited code.

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. VisitSource order: -2, 0, 3, 4. The original list remains unchanged.
  2. Filter original valuesvalue > 0 rejects -2 and 0, retaining 3 then 4.
  3. Transform kept values3 * 3 → 9; 4 * 4 → 16.
  4. New collectionA new list stores [9, 16], preserving kept-input order.
Predict before you run

Why is 4 not in the original result?

Keep positive squaresPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Include zero.

Try: Replace value > 0 with value >= 0.

The result becomes [0, 9, 16], preserving the kept inputs' order.

Remove the filter.

Try: Remove if value > 0 from the comprehension.

Every input is squared, giving [4, 0, 9, 16].

Before you move on

For [-3, 2, 2, 0], what is the new list and why?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

It is [4, 4]. Only the original positive inputs qualify; duplicates remain and zero does not pass > 0.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Make keys and values explicit

A dictionary comprehension builds key/value associations; a set comprehension keeps distinct values. The braces alone do not tell you which rule is used.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Choose whether repeated records should replace a mapping entry, remain in a list or be merged as unique values.

Words you will see

Dictionary comprehension
A key: value expression followed by iteration inside braces.
Set comprehension
A single value expression followed by iteration inside braces.
Collision of keys
Two inputs produce equal keys; later dictionary values replace earlier ones.

Notice the colon

The mapping {name: len(name) for name in names} connects each name with its length. Repeated 'Ada' creates the same key again, so the final dictionary has two entries. Updating an existing key does not move its insertion position.

The set {len(name) for name in names} has no key/value colon. Both names have length 3, so it has just one value. sorted produces [3] for stable display; it does not mean the set itself is sorted.

Choose which information may be lost

A dictionary keeps the last value for an equal key, not all records for that key. A set discards repetitions entirely. A list comprehension would preserve the length for every input: [3, 3, 3].

An empty dictionary comprehension gives {}, while an empty set comprehension gives an empty set. Plain {} means a dictionary; use set() for a literal empty set. Dictionary keys and set elements must be hashable, such as these strings and integers.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. lengths = {name: len(name) for name in names}

    The colon builds a mapping and repeated Ada updates its entry.

  2. unique_lengths = {len(name) for name in names}

    No colon: collect distinct lengths in a set.

  3. print(sorted(unique_lengths))

    Sort only for deterministic display.

A dict comprehension builds mappings; a set comprehension builds unique values. Duplicate dict keys overwrite earlier values, so decide if loss is acceptable.

Predict before you run

How many entries are in lengths?

Keys, values and uniquenessPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Add a new length.

Try: Append 'Samir' to names.

The mapping gains Samir: 5 and sorted lengths becomes [3, 5].

Compare list output.

Try: Add print([len(name) for name in names]).

It displays [3, 3, 3], keeping one result per input.

Before you move on

For ['a', 'long', 'a'], what are the distinct lengths and the number of mapping keys?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

The distinct lengths are {1, 4}, and there are two mapping keys, 'a' and 'long'. Three inputs do not require three entries in either collection.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Do not use comprehensions for side effects

A comprehension is for building data. A loop is clearer when the purpose is an action such as printing.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Avoid allocating a throwaway list of None values just to display a sequence of labels.

Words you will see

Side effect
An observable action, such as printing, beyond a returned result.
None
The value returned by print, not the text it displays.
Allocation
Creating storage for an object such as a new list.

State the intended action

The for loop visits tea then rice and print(item) displays each. There is no output collection because the purpose is presentation, not transformation.

Replacing the loop with [print(item) for item in items] would still print both lines, but also build [None, None]. Those None values are print's return values, not the displayed strings.

Choose a loop for several steps

A loop can label an item, print it, update a counter and handle a branch using ordinary statements. Compressing these steps into a comprehension obscures what changes and may create an unused list.

When items is empty the loop prints nothing, then print('done') still runs. This behavior is intentional. Printing n items requires visiting n entries; the loop does not need a separate O(n) result list.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. for item in items:

    Visit tea then rice in the stored order.

  2. print(item)

    Perform the display action for each item.

  3. print('done')

    This is outside the loop and prints once.

Writing [print(x) for x in items] constructs an unwanted list of None results. A for loop explains the purpose and avoids that allocation.

Predict before you run

How often does done print?

Use a loop for displayPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Try the empty action list.

Try: Change items to [].

Only done prints; the loop body has no items to act on.

Inspect the tempting alternative.

Try: Replace the loop with results = [print(item) for item in items]; print(results).

The extra output is [None, None], showing the unwanted result allocation.

Before you move on

What does [print(x) for x in ['a']] return after displaying a?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

It returns [None]. The display is a side effect; print itself returns None.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

A comprehension is a concise way to construct a collection from a transformation and optional filter. It should make the data relationship easier to see. If the task mainly performs logging, file writes or several state transitions, a normal loop describes the purpose more honestly.

Follow the mechanism step by step

Read the clauses in execution order: iterate a source value, evaluate its filter, then compute the result for retained values. A list comprehension materialises results; a generator expression defers production. A dict comprehension can overwrite equal keys, while a set comprehension intentionally discards duplicate membership.

Work through a concrete application

Translate a comprehension into a plain loop before using nested forms. For positive squares, the filter decides whether the original value qualifies and multiplication builds the output. For text normalisation, avoid repeating an expensive transformation in both filter and result unless the repeated cost is intentional or demonstrably negligible.

Failure cases and misleading shortcuts

A compact expression can hide substantial allocation or nested Cartesian products. Using a comprehension only to call print constructs an unwanted list of None values. Reusing the same mutable object in each result does not create independent objects, so the same aliasing concerns as ordinary loops still apply.

Cost, ownership and alternatives

Constructing n results needs O(n) output storage in addition to the cost of each transformation. A generator can reduce retained output only when downstream operations also stream; sorted or list will materialise it. Counting or summing generated values still performs their computation, even when it avoids an intermediate list.

Verify the contract

Test source preservation, an input where every item is filtered out, duplicates and transformation exceptions. For dict construction, explicitly test duplicate-key policy. Compare the comprehension's result with an easy-to-read loop on small inputs rather than assuming shorter source means a different or better algorithm.

Transfer question: Why can replacing a list comprehension with a generator change a program's behaviour?

It changes evaluation time, exception timing and consumption semantics. A generator may be exhausted by the first consumer, and external state may change before later values are produced. Choose laziness as an explicit contract rather than a universal memory optimisation.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Which builds a list of squares?
TRANSFER THE IDEA

Clean nonempty tags

Strip each tag and keep only nonempty results.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Filter before squaring

Build the squares of original positive inputs.

The contract

  • Implement positive_squares(values) for lists of integers; return a list.
  • Keep only values strictly greater than zero, then square them. Preserve order and repeated outputs.
  • Do not mutate values; [] or no positive values returns []. A comprehension or equivalent clear loop is acceptable.
Filter before squaringPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. ordinary
    r = positive_squares([-2, 0, 3, 4]); assert type(r) is list and r == [9, 16]
  2. empty
    r = positive_squares([]); assert type(r) is list and r == []
  3. duplicates
    r = positive_squares([2, 2, 1]); assert type(r) is list and r == [4, 4, 1]
  4. no matches
    r = positive_squares([-1, 0]); assert type(r) is list and r == []
  5. boundary one
    r = positive_squares([1]); assert type(r) is list and r == [1]
  6. preservation
    p = [3, -2, 1, 3]; r = positive_squares(p); assert type(r) is list and r == [9, 1, 9] and p == [3, -2, 1, 3] and r is not p
    Why not square first and keep positive results?

    That would wrongly include squares of negative inputs. Visiting n inputs costs O(n) ordinary arithmetic work and stores O(k) outputs for k kept values.

    GUIDED PRACTICE

    Clean before filtering text

    Strip tags and retain only nonempty cleaned values.

    The contract

    • Implement clean_tags(tags) for lists of strings; return a list of stripped nonempty strings.
    • Use str.strip whitespace behavior; preserve order, case and duplicates. Empty or whitespace-only tags contribute nothing.
    • Do not mutate the supplied list. No parsing, network or external package operations are needed.
    Clean before filtering textPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. ordinary
      r = clean_tags([' python ', ' ', 'sql']); assert type(r) is list and r == ['python', 'sql']
    2. empty
      r = clean_tags([]); assert type(r) is list and r == []
    3. whitespace
      r = clean_tags(['', ' ', '\t\n']); assert type(r) is list and r == []
    4. repeated
      r = clean_tags([' x ', 'x', ' y ']); assert type(r) is list and r == ['x', 'x', 'y']
    5. interior spaces
      r = clean_tags([' a b ', 'SQL']); assert type(r) is list and r == ['a b', 'SQL']
    6. preservation
      p = [' b ', '', 'a']; r = clean_tags(p); assert type(r) is list and r == ['b', 'a'] and p == [' b ', '', 'a'] and r is not p
      What can a plain loop improve here?

      It can save cleaned = tag.strip() once per tag, avoiding the repeated strip call. Both approaches take work proportional to examined text and space proportional to cleaned output; neither changes the input.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: last duplicate key wins

      Change from a list of cleaned tags to a dictionary keyed by lowercase cleaned tags.

      The contract

      • Implement last_lengths(tags) for lists of strings; strip each tag and ignore blank results.
      • Key is cleaned.lower(); value is len(cleaned). Last occurrence of an equal key replaces its value; retain first-key insertion order.
      • Return a dict, not a list or set; preserve the input. Length is Python string length, not display width.
      Transfer: last duplicate key winsPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. ordinary mapping
        r = last_lengths([' Py ', 'SQL']); assert type(r) is dict and r == {'py': 2, 'sql': 3}
      2. empty
        r = last_lengths([]); assert type(r) is dict and r == {}
      3. blank filtering
        r = last_lengths([' ', '\n', ' x ']); assert type(r) is dict and r == {'x': 1}
      4. last occurrence
        r = last_lengths(['İ', 'i\u0307']); assert type(r) is dict and r == {'i\u0307': 2}
      5. insertion order
        r = last_lengths(['B', 'a', 'b']); assert type(r) is dict and r == {'b': 1, 'a': 1} and list(r) == ['b', 'a']
      6. preservation
        p = [' Ab ', '', 'c']; r = last_lengths(p); assert type(r) is dict and r == {'ab': 2, 'c': 1} and p == [' Ab ', '', 'c']
        Why use the two Unicode inputs in a collision check?

        Lowercasing can change string length: capital İ has length 1 and lowercases to i plus a combining dot, length 2. A later equivalent key must replace the first length. Work is proportional to processed text on average under ordinary hash-table assumptions; stored keys and values need output-sized space.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Lazy versus eager

        A generator expression delays output computation and is consumed once. A list comprehension computes and stores every result immediately.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Sum squares without retaining a second list when no caller needs the individual squares afterwards.

        Words you will see

        Generator expression
        An expression such as (x*x for x in data) that produces a generator iterator.
        Eager result
        A fully built collection available for reuse.
        Lazy result
        Values computed as a consumer requests them.

        Trace the consumer

        The parentheses create a generator expression, not a tuple of squares. sum(stream) requests 4, 9 and 16 and returns 29. list(stream) then sees exhaustion and returns [].

        The generator does not make the original values list disappear. It saves the extra squares list only because sum does not retain each intermediate output. sum(value * value for value in values) can express the same single-consumer use directly.

        Do not overpromise delayed behavior

        A generator expression evaluates its outermost iterable expression when created; its output expression runs during consumption. Avoid claiming no part of its setup is evaluated until next.

        If the same result is needed twice, keep a list or make a new generator from a reusable source. With n ordinary numbers, both forms do O(n) arithmetic, but a list of squares needs O(n) result storage while this sum does not.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. stream = (value * value for value in values)

          Create an advancing stream of computed squares.

        2. print(sum(stream))

          Consume 4 + 9 + 16 to print 29.

        3. print(list(stream))

          There are no remaining generated values.

        A generator expression (x * x for x in data) produces values on demand. A list comprehension stores all results. Use sum(x * x for x in data) when you only need a total, not a reusable list.

        Predict before you run

        What is the last printed value?

        Sum without storing all squaresPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Make the result reusable.

        Try: Replace parentheses around the comprehension with square brackets.

        The second print now displays [4, 9, 16], because stream is a list.

        Test no values.

        Try: Set values = [].

        sum prints 0 and the exhausted stream prints [].

        Before you move on

        Can you call sum(stream) twice and expect 29 both times?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. The first call exhausts stream; the second returns 0. Keep a reusable list or create a fresh generator for the second traversal.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Count all combinations

        Multiple for clauses nest from left to right. Flattening visits existing entries; a Cartesian product creates every cross-combination.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Estimate output size before replacing two loops with a compact expression that may build a very large list.

        Words you will see

        Flatten
        Visit each row and then each item within that row.
        Cartesian product
        Every combination of one item from each source.
        Output-sensitive cost
        Work or storage described using how many results must actually be produced.

        Expand the written loop order

        [item for row in rows for item in row] first chooses a row, then visits that row's items. For [[1, 2], [], [3]], the empty middle row contributes no item, so the flat result is [1, 2, 3].

        [(a, b) for a in [1, 2] for b in ['x', 'y']] holds a fixed while b runs through both letters. The pairs are (1, 'x'), (1, 'y'), (2, 'x'), (2, 'y'). Reversing the for clauses changes the traversal order.

        Count work by the data shape

        Flattening r rows containing m total entries takes O(r + m) traversal work and O(m) result references. A product of p and q items creates p*q pairs, so eager output needs O(p*q) time and space.

        A generator expression can delay storing those pairs, but consuming all of them still does that much work. Both examples build new outer lists; nested mutable elements would still be shared references, not recursive copies.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. flat = [item for row in rows for item in row]

          Visit each row, then each existing entry within it.

        2. pairs = [(a, b) for a in [1, 2] for b in ['x', 'y']]

          For each a, visit every b before advancing a.

        3. print(pairs)

          Display four pairs in the explicit nested-loop order.

        Nested comprehensions can multiply work. Flattening rows traverses all elements; taking every pair from two length-n collections creates n squared outputs and needs corresponding space if materialised.

        Predict before you run

        Why are there four pairs?

        Flatten is not all pairsPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Add an empty row.

        Try: Append [] to rows.

        The flat list stays [1, 2, 3]; empty rows add no output entries.

        Reverse product traversal.

        Try: Swap the product clauses to for b in ['x', 'y'] for a in [1, 2].

        The middle pairs change order: both x pairs now precede both y pairs.

        Before you move on

        If there are three a values and no b values, how many pairs are built?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        Zero. Each inner traversal is empty, so no output expression runs, even though the outer loop visits three values.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.