smartyfy.mrindigi.com

Python Master Course V2 — 045. Sets Fundamentals

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 05 · LESSON 045/200

Sets Fundamentals

Estimated study: 75–100 minutes · Prerequisite: Lesson 044 and earlier collections lessons.

Video lesson

Video not yet available. A dedicated space is reserved for a verified video URL or player.

Learning outcomes

  • Explain the behavior and use cases of sets fundamentals.
  • Apply the correct Python syntax and predict output.
  • Handle missing, duplicate and invalid data deliberately.
  • Implement a practical real-world processing project.
  • Write edge-case tests and explain failures.

Detailed explanation

A set stores unique hashable values. It is unordered, so sort values explicitly for a predictable report.

Begin by defining the expected data types, key constraints, and the output contract. Consider whether the operation creates a new collection or mutates an existing one. For reports, sort results where stable ordering matters. When records represent business data, missing information should be reported rather than silently replaced unless a clear rule permits defaults.

Professional Python code benefits from small functions, descriptive names, explicit validation and repeatable tests. Assess the complexity of nested operations when data volumes grow.

Understand Sets Fundamentals

Use a set when presence matters

A set represents distinct values. It answers “is this code present?” and “which different codes occurred?” without preserving how often each value occurred. Converting ["A", "B", "A"] to a set produces two members. This is ideal for unique tags or a membership index, but it is the wrong structure for quantities, duplicate-sensitive transactions or a sequence whose original order matters.

Create a nonempty set with braces around values, such as {"A", "B"}. Create an empty set with set(); empty braces mean an empty dictionary. The set constructor accepts an iterable, so set("book") contains individual characters, not the word book. Write {"book"} for a one-word set. Sets are not indexed: codes[0] is invalid even if a printed set looks like a sequence.

Python
codes = ["A", "B", "A", "C", "B"]
unique = set(codes)
print(len(codes), len(unique))
print(sorted(unique))
print("D" in unique)
print(sorted(set("book")))
Expected output
5 3
['A', 'B', 'C']
False
['b', 'k', 'o']

The list length counts observations; the set length counts distinct values. sorted creates a list for deterministic display and leaves the set unchanged. Set iteration order should not be treated as an application contract, even if it looks stable in one run. Sort only comparable values; mixing unrelated types such as integers and strings may raise TypeError during sorting. Choose one identifier type for the entire dataset.

Change membership deliberately

Python
present = {"A", "B"}
present.add("C")
present.add("A")
present.remove("B")
present.discard("missing")
print(sorted(present))
Expected output
['A', 'C']

add includes a member and does nothing extra if that member already exists. remove raises KeyError if the requested member is absent, making it appropriate when membership is required. discard tolerates absence, so it fits “ensure this code is no longer present”. These methods mutate the original set and return None. Set pop removes an arbitrary member, not the oldest or smallest one; use an explicit rule when selection order matters.

Hashability and duplicate evidence

Set members must be hashable. A tuple of strings works; a list or dictionary does not. If you need a collection of records, keep records in a list and extract their stable IDs into a separate set. Values that compare equal, such as 1 and True, can collapse into one member, so do not mix booleans and numeric identifiers. Validation should establish a single domain before deduplication hides differences.

For the unique-code project, preserve the original list until the duplicate policy is decided. You can report duplicate observations as len(codes) - len(set(codes)), but that count does not identify which codes repeated. To keep first-seen order, use a seen set alongside an output list: append a code only on its first encounter, then add it to seen. The two structures serve different needs, membership and presentation, without pretending that a set is ordered.

Runnable example

Setup: Python 3.10+, standard library only. Save the following as lesson_045.py and run python lesson_045.py. The output is expected, not a claim of execution on Smartyfy.

codes=["A","B","A","C","B"]
unique=set(codes)
print(sorted(unique))
print("A" in unique)

Expected output:

['A', 'B', 'C']
True

Walkthrough: Identify the starting collection, trace each operation and compare the final state with the expected output. Change one input to verify your understanding.

Real-world project — Sets Fundamentals in practice

Build a reusable Python function for a realistic record-processing workflow. Keep the calculation separate from user interaction and make output deterministic.

def unique_codes(codes):
    return sorted(set(codes))
print(unique_codes(["SO1","SO2","SO1","SO3"]))

Expected output:

['SO1', 'SO2', 'SO3']

Extra project: Add validation for malformed records, a CSV export, summary totals, and five independent tests. Cover empty data, duplicates, one-sided missing records and large inputs where applicable. Explain how your algorithm’s running time grows with the input size.

Common mistakes and best practices

  • Assuming all required keys and values exist.
  • Confusing ordered and unordered collections.
  • Overwriting duplicate dictionary keys without realizing it.
  • Accidentally mutating shared nested data.
  • Ignoring edge cases or using unsafe defaults for missing business records.

Practice and explained answers

Try each question before opening its answer. Predict code results on paper, then compare them with the explanation.

Optional hint for question 1

Compare the notation for key/value pairs with the constructor for an empty collection.

1. Why does {} not create an empty set?

Answer and reasoning:

Python reserves empty braces for a dictionary. Use set() to create a set; {"A"} is a nonempty set because there is no key/value colon.

2. What is len(set([1, 1, 2, 2, 2]))?

Answer and reasoning:

It is 2, representing members 1 and 2. It is not 5, because the set does not retain occurrence counts.

3. When should remove be preferred to discard?

Answer and reasoning:

Use remove when absence is an error you want to expose. Use discard when the requested outcome is simply “member absent”, regardless of whether it was present before. Both remove an existing member in place.

4. Deduplicate while preserving the first-seen order.

Answer and reasoning:

Python
codes = ["B", "A", "B", "C"]
seen = set()
result = []
for value in codes:
    if value not in seen:
        result.append(value)
        seen.add(value)
print(result)
Expected output
['B', 'A', 'C']

The set supports membership checks; the list records the desired order. Sorting the set would instead give alphabetical order.

5. Can a set verify that two lists have identical duplicates?

Answer and reasoning:

No. set(["A", "A"]) equals set(["A"]). If counts matter, build a dictionary of counts and compare it, or later use collections.Counter.

Mastery checkpoint

Explain sets fundamentals, predict the code output, run the project and create three new tests, including a failure case.

Summary: A set stores unique hashable values. It is unordered, so sort values explicitly for a predictable report.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.