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 11 / COLLECTIONS IN DEPTH

Sets: membership and uniqueness

Describe unique values and relationships between collections.

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
  • Deduplicate hashable values
  • Use union/intersection/difference
  • Choose set versus list
01

A set answers 'is it present?'

A set represents which distinct values are present. It does not record how many times a value arrived or give it a stable position.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use a set for selected skills, visited nodes or repeated membership checks. Use a list when order or repeated occurrences are part of the information.

Words you will see

Unique / distinct
Equal values count as one member, not multiple occurrences.
Membership
Whether a value belongs to a set.
Unordered
No positional indexing or promised iteration order; not the same as randomly reshuffling on every read.

Build presence, not a sequence

{"python", "sql"} creates a nonempty set. set() creates an empty one, while {} creates a dictionary. set(["sql", "sql", "python"]) keeps two distinct values. There is no skills[0]; a set is not a sequence with hidden integer indexes.

Use "sql" in skills to ask about presence and len(skills) to count distinct members. Removing duplicates loses information deliberately: a set of arrivals cannot later tell you how many times Ada arrived. Do not convert an ordered history to a set and expect to recover it.

Separate the stored relation from its display

The example compares two skill sets. first & second selects skills present in both. first | second selects skills present in either. first - second selects skills in first that are absent from second.

sorted(...) creates a list only for predictable display in this example. It does not sort the underlying sets. Set representations and iteration order can differ between runs or environments, so tests should compare set values or deliberately sorted displays, not one incidental printing order.

Use values that support set membership

Strings are suitable members. An ordinary list is not: sets need hashable values, a stable lookup contract explained in optional depth. A set of immutable identifiers and an ordered result list often solve different parts of the same problem.

The original example, step by step

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

  1. first = {"python", "sql"}

    Create the first two unique skills.

  2. print(sorted(first & second))

    Find shared sql, then display it in a sorted list.

  3. print(sorted(first | second))

    Combine unique skills from both sources: java, python and sql.

  4. print(sorted(first - second))

    Keep only python, which occurs in first but not second.

Use a set for unique tags, visited graph nodes or repeated membership queries. A set has no positional indexing or guaranteed iteration order. Use set() for an empty set; {} creates an empty dict.

Choose the relationship, not an item position.

This model represents membership, not Python execution. Names are sorted for display only; no set iteration order is promised.

Required: java, python

Selected: python, sql

shared: ["python"]

Predict before you run

Why does the example sort its results?

Find shared skillsPYTHON 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 repeated skill.

Try: Build first from ["python", "sql", "sql"] with set(...).

Sql remains one member and the set relations are unchanged.

Distinguish empty collections.

Try: Compare print(type({})) with print(type(set())).

The first is dict and the second is set.

Before you move on

What information is lost by converting ["Lin", "Ada", "Lin"] to a set? Does sorted change that set?

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 repeated Lin and the original sequence are lost. sorted returns a new sorted list of the distinct values; it does not restore the history or change the set into ordered storage.

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

Set operations model relationships

Set operations express relationships between memberships. Mutation methods change an existing set; relation expressions usually return a result set.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Skill gaps, permission comparisons and selected filters are relationship questions. Expressing the correct direction matters more than writing the shortest operator.

Words you will see

Intersection / union
Members shared by both sets / members in either set.
Difference
Members in the left set that are not in the right set.
Symmetric difference
Members in exactly one of the two sets, written ^.

Read the relation in words

required - selected asks which required skills are missing. selected - required asks about extra selected skills. Those are different questions. Intersection and union can swap their operands without changing the members; difference generally cannot.

a <= b asks whether every member of a belongs to b, including equality. a < b requires a proper subset, so equal sets do not satisfy it. a.isdisjoint(b) asks whether they share no members. Symmetric difference excludes members shared by both.

Choose whether the original changes

add inserts one hashable member and does nothing extra for an equal existing member. update adds members from an iterable. discard removes a member if present; remove raises KeyError if absent. pop removes an arbitrary member, not a promised first or last item. clear empties the set.

Mutation methods such as add, update and discard return None. a | b creates a result; a |= b updates a. Method forms can accept iterables in places where the binary set operators require set-like operands. Define whether absence is allowed instead of swallowing every error.

The original example, step by step

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

  1. selected.add("sql")

    Adding an existing member does not make a duplicate.

  2. selected.discard("java")

    Missing java is allowed by discard.

  3. print(sorted(required - selected))

    Read the relation in the required-to-selected direction: java is missing.

  4. print(sorted(required ^ selected))

    Java and sql are in exactly one side.

  5. selected.remove("java")

    The stricter removal raises KeyError, which this example explains.

& is intersection, | union and - difference. add inserts a value; discard removes it if present, whereas remove raises KeyError when missing.

Predict before you run

Does discard of missing java raise KeyError?

Change presence and compare groupsPYTHON 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.

Reverse the gap question.

Try: Compare sorted(required - selected) with sorted(selected - required).

The first reports missing required skills; the second reports extra selected skills.

Compare subset with proper subset.

Try: Print selected <= selected, then selected < selected.

Every set is a subset of itself, but not a proper subset of itself.

Before you move on

For required = {"a", "b"} and completed = {"b", "c"}, what are missing and extra?

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

missing = required - completed is {"a"}. extra = completed - required is {"c"}. The shared member b belongs to neither difference.

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

Choose semantics first

Sometimes you need both fast membership and first-occurrence order. Use a set to remember what was seen and a list to store the ordered result.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

An activity feed may want one card per person in first-appearance order. Alphabetical sorting or converting the final set back to a list would answer a different question.

Words you will see

First occurrence
The earliest equal value encountered in the input.
Seen set
Membership memory used to avoid emitting a repeated value.
Invariant
A statement that stays true as each loop step completes.

Give each structure one responsibility

Before the loop, seen and ordered are empty. For the first Lin, membership is false, so add Lin to seen and append Lin to ordered. Ada follows the same path. The second Lin is already present, so neither structure changes. Sam is then appended once.

After every step, seen contains exactly the values emitted so far, and ordered keeps their first-appearance order. This invariant explains why both duplicates and ordering are handled correctly. The input list is only read.

Do not simplify away the requirement

list(set(visitors)) produces distinct values without a first-occurrence ordering promise. sorted(set(visitors)) deliberately gives sorted order instead. Both can look plausible on a small example and still violate the required semantics.

For n input values and u distinct values, the explicit loop takes average O(n) time and O(u) additional storage under ordinary hash-table assumptions. The two structures both grow with distinct values, not with every repeated occurrence. Unhashable nested values require a different equality/key policy rather than an unexplained conversion to strings.

The original example, step by step

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

  1. seen = set()

    Create membership memory; {} would have created a dictionary.

  2. ordered = []

    Keep the output sequence separately.

  3. if visitor not in seen:

    Only the first occurrence of a value enters this branch.

  4. seen.add(visitor)

    Remember that the value has now been emitted.

  5. ordered.append(visitor)

    Keep that first occurrence at the end of the ordered result.

If order or duplicates matter, do not replace a list with a set blindly. A seen set plus a result list can efficiently preserve first-occurrence order.

Predict before you run

Which visitor appears first in ordered?

Keep the first occurrence, not sorted orderPYTHON 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.

Change the first arrival.

Try: Move "Sam" to the beginning of visitors.

Sam becomes first in ordered without any sorting.

Compare a plausible wrong answer.

Try: Print sorted(set(visitors)) as well.

The unique values match, but the order answers a different question.

Before you move on

What should first-occurrence deduplication return for ["b", "a", "b", "c"]? Why is ["a", "b", "c"] different?

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 should return ["b", "a", "c"]. The alphabetically sorted alternative loses the first-arrival ordering requirement, even though it has the same distinct values.

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 set represents uniqueness and membership rather than position or multiplicity. It is useful for visited nodes, allowed values and deduplication keys. Before replacing a list, ask whether the caller needs original order, repeated occurrences or stable display; losing those properties is a semantic change, not just an optimisation.

Follow the mechanism step by step

A set uses hash/equality semantics similar to dict keys. Adding an equal element does not create another occurrence. Union combines membership, intersection keeps shared members and difference removes membership found in the other set. An empty set is constructed with set(), because empty braces create a dict.

Work through a concrete application

For order-preserving deduplication, keep a seen set and append first occurrences to a separate list. Trace a repeated name through both structures to see why membership state and output order are separate responsibilities. For permission comparisons, write out the direction of difference; requested minus allowed is not equivalent to allowed minus requested.

Failure cases and misleading shortcuts

Set iteration order should not be presented as sorted or stable across processes. Unhashable nested lists cannot be inserted directly, and converting mutable records to arbitrary strings can introduce collisions in domain meaning. discard tolerates an absent element; remove raises KeyError. Choose that difference according to whether absence is expected.

Cost, ownership and alternatives

Expected constant-time membership trades additional hash-table storage for repeated scan cost. Building a set from n items takes work and retains distinct elements; it is not worthwhile for every one-off tiny lookup. Large intersections and unions allocate results, so consider the complete operation and input cardinalities.

Verify the contract

Test duplicates, empty sets, disjoint inputs, complete overlap and the direction of difference. Compare sets as sets unless display ordering is part of the output contract, in which case sort explicitly using an agreed key. Check that the selected identity key really distinguishes the entities the application cares about.

Transfer question: How would you report duplicate IDs while preserving their original occurrence counts?

Use a Counter or dict of counts rather than only a set, since a set discards multiplicity. A set can help recognise first observations, but the reporting contract requires retaining count information and perhaps a separate order list.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

How do you create an empty set?
TRANSFER THE IDEA

One-time visitors

Print unique visitors in sorted order.

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

Guided: find shared skills

Return shared membership without changing either supplied set.

The contract

  • Inputs are sets of skill-name strings.
  • Return a new set of skills present in both inputs.
  • Do not mutate inputs or return a sorted list; empty and disjoint inputs give an empty set.
Guided: find shared skillsPYTHON 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. shared member
    assert shared_skills({"python", "sql"}, {"sql", "java"}) == {"sql"}, "Select shared skills"
  2. disjoint
    assert shared_skills({"a"}, {"b"}) == set(), "Disjoint means empty"
  3. empty input
    assert shared_skills(set(), {"a"}) == set(), "Empty input has no shared skill"
  4. equal inputs
    assert shared_skills({"a", "b"}, {"b", "a"}) == {"a", "b"}, "Equal sets keep all members"
  5. set type
    assert isinstance(shared_skills({"a"}, {"a"}), set), "Return a set"
  6. ownership
    first = {"a", "b"}
    second = {"b", "c"}
    result = shared_skills(first, second)
    assert isinstance(result, set) and result == {"b"} and first == {"a", "b"} and second == {"b", "c"} and result is not first and result is not second, "Return a new intersection set and preserve both inputs"
    Why not sort before returning?

    The contract asks for membership, not a display sequence. Intersection can inspect the smaller set, giving average O(min(a, b)) membership work for sizes a and b with suitable hashing; result storage grows with shared members.

    GUIDED PRACTICE

    Guided: unique visitors in arrival order

    Combine membership memory with an ordered result.

    The contract

    • Input is a list of strings.
    • Return a new list containing only each string's first occurrence, in original relative order.
    • Preserve case distinctions and input contents; empty input gives an independent empty list.
    Guided: unique visitors in arrival orderPYTHON 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. first occurrence
      assert unique_in_order(["Lin", "Ada", "Lin", "Sam"]) == ["Lin", "Ada", "Sam"], "Preserve first appearance"
    2. empty
      assert unique_in_order([]) == [], "Empty input gives no visitors"
    3. all repeated
      assert unique_in_order(["a", "a", "a"]) == ["a"], "Keep one occurrence"
    4. case-sensitive
      assert unique_in_order(["a", "A", "a"]) == ["a", "A"], "Do not normalise case"
    5. input preserved
      items = ["b", "a", "b"]
      result = unique_in_order(items)
      assert result == ["b", "a"] and items == ["b", "a", "b"] and result is not items, "Do not edit or alias the history"
    6. independent calls
      assert unique_in_order([]) is not unique_in_order([]), "Return independent mutable results"
      Why are both a set and a list useful?

      The set answers whether the value was already emitted; the list records first-appearance order. For n items and u distinct strings, average time is O(n) and additional storage O(u), under ordinary hashing assumptions.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: report the remaining requirements

      Change the question from shared membership to a directional gap.

      The contract

      • Inputs are lists or sets of requirement-name strings.
      • Return a fresh set of required names absent from completed; repeated names count as one requirement.
      • Preserve both input collections. Extra completed names must not appear in the result.
      Transfer: report the remaining requirementsPYTHON 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. direction
        assert missing_requirements(["a", "b"], ["b", "c"]) == {"a"}, "Report missing, not extra"
      2. duplicates
        assert missing_requirements(["a", "a", "b"], []) == {"a", "b"}, "Requirements are memberships"
      3. all completed
        assert missing_requirements({"a"}, {"a", "extra"}) == set(), "Extra completion is not missing"
      4. empty required
        assert missing_requirements([], ["a"]) == set(), "No requirements means no gap"
      5. case
        assert missing_requirements(["A", "a"], ["a"]) == {"A"}, "Names are case-sensitive"
      6. ownership
        required = {"a", "b"}
        completed = {"b"}
        result = missing_requirements(required, completed)
        assert isinstance(result, set) and result == {"a"} and required == {"a", "b"} and completed == {"b"} and result is not required and result is not completed, "Return the missing set and keep caller collections intact"
        Why does intersection no longer solve this problem?

        Intersection reports what is already shared; difference reports what is required but absent. For r required and c completed entries, construction and difference use average O(r + c) time and O(r + c) extra storage as an upper bound under ordinary hashing assumptions.

        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

        Hashability and cost

        Sets use hashes and equality for membership. Their average lookup advantage depends on hashable values, while building and copying a set still take time and space.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A set of visited identifiers can speed up repeated checks. A set of arbitrary mutable records may be invalid, and rebuilding a membership set for every query can waste its benefit.

        Words you will see

        Hashable
        Supports a stable hash with equality consistent with that hash.
        frozenset
        An immutable set-like value that can itself be hashable.
        Average case
        Expected work under ordinary hashing conditions, not a bound for every possible input.

        A hash narrows the search; equality decides membership

        Different values may share a hash, so hashes are not unique IDs. Equal values must have equal hashes. Lists and ordinary sets are unhashable; tuples of hashable members and frozensets can be used as members or dictionary keys.

        The frozenset built from sql and python equals the one built in the opposite order, so the dictionary lookup finds the same group. Also, 1, True and 1.0 compare equal in Python; a set of all three has one member, not three type-specific memberships.

        Account for construction and memory

        Membership, adding and discarding are average O(1) with bounded-cost hashing/equality, but collisions can degrade operations toward O(n). Building n distinct memberships uses O(n) work on average and O(n) storage. Repeatedly calling set(items) inside every membership query rebuilds that work.

        Intersection generally benefits from inspecting the smaller set; union must represent members from both. Exact implementation costs depend on operands and operation choice. A frozen set prevents adding/removing outer memberships, not every possible mutation of custom objects reached through its members.

        The original example, step by step

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

        1. group = frozenset({"python", "sql"})

          Create a hashable unordered group of strings.

        2. print(lookup[frozenset({"sql", "python"})])

          Use an equal group, built in a different order, to find backend.

        3. print(len({1, True, 1.0}))

          Display 1 because the numeric values compare equal.

        4. set([[1, 2]])

          An inner list cannot be a set member; the example catches TypeError.

        Like dicts, sets use hashes: membership is expected O(1) average with worst-case degradation. Building a set of n values uses O(n) space. Elements must be hashable; a frozenset is useful for an immutable set-like key.

        Predict before you run

        How many members are in {1, True, 1.0}?

        Frozen groups and equal numeric membersPYTHON 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.

        Use a genuinely different number.

        Try: Replace 1.0 with 2.0.

        There are now two distinct numeric memberships.

        Try a mutable group key.

        Try: Replace frozenset({"python", "sql"}) with {"python", "sql"} in the assignment to group.

        Using the ordinary set as a dictionary key raises TypeError.

        Before you move on

        Can a normal set be a dictionary key? Why can a frozenset of strings be one?

        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

        An ordinary set is mutable and unhashable. A frozenset of hashable strings supports stable hashing and equality; the order used to build it does not affect set equality.

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

        Order-preserving deduplication

        An ordered dictionary can be another deduplication tool for hashable values. It preserves first key insertion, but it does not make arbitrary nested objects hashable.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A concise expression is useful when its assumptions are already understood. You should be able to explain why it preserves order rather than relying on a memorised idiom.

        Words you will see

        fromkeys
        Build a dictionary with the supplied distinct keys and a common value.
        Insertion-ordered keys
        A dictionary keeps the first insertion position of each key.
        Equality policy
        The rule deciding when two supplied records count as the same value.

        Explain the short form through the longer rule

        dict.fromkeys(items) inserts each value as a key with a default value of None. A repeated equal key does not acquire a new position. Converting the dictionary to a list reads the keys in first-insertion order, giving the same output rule as the seen-set loop.

        The common value does not matter when only keys are used. Do not repurpose dict.fromkeys(names, []) as independent lists for grouping: every key would refer to the same supplied list. Build a fresh list per key when independent mutation is required.

        Choose a policy for values that are not hashable

        Nested lists cannot directly become set members or dictionary keys. If two records should be identified by a stable string ID, deduplicate on that ID deliberately. If whole nested contents define equality, choose and explain a compatible representation or an equality-based scan.

        An equality-based list scan can be quadratic for n inputs because each new item may compare against many earlier results. That can be acceptable for small inputs, but it is not the same performance contract as average linear hashing. Never stringify arbitrary values silently: different logical objects may then acquire the same display text.

        The original example, step by step

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

        1. result = list(dict.fromkeys(items))

          Keep each key's first position, then read the keys into a list.

        2. print(result)

          Display b, a, c in first-appearance order.

        3. print(list(dict.fromkeys([])))

          Empty input produces an empty list.

        4. dict.fromkeys([[1], [1]])

          The unhashable list keys fail explicitly rather than being silently converted.

        For hashable values, list(dict.fromkeys(items)) retains first-insertion order in modern Python. Explain the assumption; it is not a solution for arbitrary unhashable nested objects.

        Predict before you run

        Which order does the result preserve?

        Two ways to preserve first occurrencePYTHON 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.

        Start with a different value.

        Try: Use items = ["c", "b", "c", "a"].

        The result becomes ['c', 'b', 'a'].

        Expose a shared-default trap.

        Try: Build groups = dict.fromkeys(["a", "b"], []), append through groups["a"], then print(groups["b"]).

        Both keys refer to the one supplied list; fromkeys does not clone it per key.

        Before you move on

        Why is list(dict.fromkeys(["z", "a", "z"])) not alphabetical? What happens with list-valued input items?

        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 ["z", "a"] because dictionary keys preserve first insertion, not sorting. List-valued items are unhashable and raise TypeError unless you explicitly choose another representation or equality policy.

        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.