Sets: membership and uniqueness
Describe unique values and relationships between collections.
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.
- Deduplicate hashable values
- Use union/intersection/difference
- Choose set versus list
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.
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.
first = {"python", "sql"}Create the first two unique skills.
print(sorted(first & second))Find shared sql, then display it in a sorted list.
print(sorted(first | second))Combine unique skills from both sources: java, python and sql.
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"]
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.
Set operations model relationships
Set operations express relationships between memberships. Mutation methods change an existing set; relation expressions usually return a result set.
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.
selected.add("sql")Adding an existing member does not make a duplicate.
selected.discard("java")Missing java is allowed by discard.
print(sorted(required - selected))Read the relation in the required-to-selected direction: java is missing.
print(sorted(required ^ selected))Java and sql are in exactly one side.
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.
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.
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.
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.
seen = set()Create membership memory; {} would have created a dictionary.
ordered = []Keep the output sequence separately.
if visitor not in seen:Only the first occurrence of a value enters this branch.
seen.add(visitor)Remember that the value has now been emitted.
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.
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.
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.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
One-time visitors
Print unique visitors in sorted order.
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 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.
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: 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.
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.
- first occurrence
assert unique_in_order(["Lin", "Ada", "Lin", "Sam"]) == ["Lin", "Ada", "Sam"], "Preserve first appearance"
- empty
assert unique_in_order([]) == [], "Empty input gives no visitors"
- all repeated
assert unique_in_order(["a", "a", "a"]) == ["a"], "Keep one occurrence"
- case-sensitive
assert unique_in_order(["a", "A", "a"]) == ["a", "A"], "Do not normalise case"
- 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"
- 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: 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.
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.
- direction
assert missing_requirements(["a", "b"], ["b", "c"]) == {"a"}, "Report missing, not extra" - duplicates
assert missing_requirements(["a", "a", "b"], []) == {"a", "b"}, "Requirements are memberships" - all completed
assert missing_requirements({"a"}, {"a", "extra"}) == set(), "Extra completion is not missing" - empty required
assert missing_requirements([], ["a"]) == set(), "No requirements means no gap"
- case
assert missing_requirements(["A", "a"], ["a"]) == {"A"}, "Names are case-sensitive" - 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.
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 milestoneHashability 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.
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.
group = frozenset({"python", "sql"})Create a hashable unordered group of strings.
print(lookup[frozenset({"sql", "python"})])Use an equal group, built in a different order, to find backend.
print(len({1, True, 1.0}))Display 1 because the numeric values compare equal.
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.
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.
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.
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.
result = list(dict.fromkeys(items))Keep each key's first position, then read the keys into a list.
print(result)Display b, a, c in first-appearance order.
print(list(dict.fromkeys([])))Empty input produces an empty list.
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.
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.
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.
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.