Set Collections: Unique Values and Membership

When a program tracks registered participants, available tags, or completed tasks, repeated values may add no useful information. A set collection stores distinct elements without a guaranteed order. Python provides this behavior through its built-in set type. Use it when the important questions are which values are present and how groups overlap, rather than where values occur.

Create a collection and test membership

Write a nonempty set with braces and comma-separated elements:


Python
rooms = {"east", "west", "east"}


The collection contains two distinct strings: "east" and "west". Repeating "east" does not create another stored copy. len(rooms) therefore returns 2, counting distinct elements rather than the values written in the original expression.


Create an empty set with set(). Empty braces, {}, create a different collection type, so they do not initialize an empty set.


Example: For the room collection above, "east" in rooms returns True, while "north" in rooms returns False. Use not in when you need to test absence.


Sets provide no guaranteed insertion order or positional indexing. You cannot use rooms[0] to retrieve the first room. A displayed order is not a promise about future output, and two sets are equal when they contain the same elements, regardless of display order.


Elements must be hashable. Integers and strings work for the examples here. A mutable set cannot itself be an element of another ordinary set.

Change the stored elements

A set is mutable: you can change its contents after creating it. rooms.add("north") inserts the new string. Adding "north" again leaves the contents unchanged because the value is already present.


Use rooms.remove("west") when you expect an element to exist. If it is absent, Python raises KeyError. Use rooms.discard("west") when absence is acceptable; an absent value causes no error.


These methods change the existing collection and return None, rather than returning the updated set. Call the method on its own line:


Python
rooms.add("south")



Combine collections

Set operations create collections by selecting elements according to membership in two inputs. For the operator forms below, both inputs are sets.


Operation

Python expression

Elements kept

Union

A \| B

Present in either input, including both

Intersection

A & B

Present in both inputs

Difference

A - B

Present in A but absent from B

Reverse difference

B - A

Present in B but absent from A

Symmetric difference

A ^ B

Present in exactly one input


Two overlapping regions show members belonging only to A, to both collections, or only to B.


These expressions produce new sets; they leave the input collections unchanged. Difference is directional, so reversing its inputs can change the result. Union and intersection do not depend on which input comes first.


When counting a union, subtract the shared elements because adding the two input counts includes them twice:


∣A∪B∣=∣A∣+∣B∣−∣A∩B∣|A \cup B| = |A| + |B| - |A \cap B|


Here, ∣A∣|A| means the number of distinct elements in A, calculated by len(A). The union and intersection correspond to A | B and A & B.



What to remember

  • Use set() for an empty set and in for membership.
  • Duplicate additions do not increase the number of elements.
  • Use add, remove, and discard to update contents.
  • Check the direction of a difference before calculating its result.
  • Compare contents rather than printed order.

Example: Tracking Workshop Clearances

A workshop records participant IDs for safety training and equipment training. Repeated entries can occur in the safety record. Treat each ID as an exact, case-sensitive string, and use Python sets to track distinct participants.


Python
safety = {"P11", "P14", "P11", "P18", "P20"}
equipment = {"P14", "P20", "P22"}


a) How many distinct participants are in safety?


First account for repeated IDs. Among the first three entries, "P11", "P14", and "P11", there are ________ distinct IDs. The repeated "P11" contributes no additional element.


The remaining entries, "P18" and "P20", are both new. The complete collection therefore contains "P11", "P14", "P18", and "P20".


Python
len(safety)


The result is 4 distinct participants. The count concerns unique IDs, rather than the five entries written in the original expression.


b) Participants need both types of training to use the equipment. Find their IDs and their number.


An intersection keeps elements present in both input collections. Test each safety ID against equipment. For "P14", the test ("P14" in safety) and ("P14" in equipment) is ________. For "P22", the corresponding both-collections test is ________ because that ID is absent from safety.


Python
cleared = safety & equipment


The shared members are "P14" and "P20". The IDs "P11" and "P18" lack equipment training, while "P22" lacks safety training.


Python
len(cleared)


The cleared IDs are P14 and P20, giving 2 participants. Their display order does not affect membership or the count.


c) Continuing from the original collections, remove P18 from safety and add P22 to safety. Which participants then have safety training but lack equipment training, and how many are there?


Apply the updates before calculating the difference. Discarding "P18" leaves ________ distinct safety IDs:


Python
safety.discard("P18")


Adding the new safety ID "P22" increases the safety count to ________:


Python
safety.add("P22")


The updated safety members are "P11", "P14", "P20", and "P22". The equipment collection remains unchanged. Select members of the updated safety collection that are absent from equipment:


Python
waiting = safety - equipment


The IDs "P14", "P20", and "P22" all belong to equipment, so the difference contains only "P11". Reversing the subtraction would answer a different question.


The participant is P11, and the number awaiting equipment training is 1 participant.

At a school event, a Python set stores attendee IDs from repeated entrance scans. Staff need distinct attendees without tracking arrival order. Which description correctly explains the collection's behavior?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A library scanner needs an empty set, a collection containing no elements, before it begins recording badge identifiers. Complete the following statements using exact Python syntax.


The expression assigned to seen to create an empty Python set is .


After identifiers have been added, the operator placed between badge and seen to test whether that identifier belongs to the set is .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A training centre records badge IDs attending two sessions using the following Python sets:


Python
A = {102, 105, 108, 112}
B = {105, 112, 116}


Complete the table with the number of distinct badges in each category. Enter exact integers. Either session includes badges attending both; exactly one session excludes badges attending both.

CategoryNumber of distinct badges
Either session
Both sessions
Session A but not session B
Session B but not session A
Exactly one session

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice