Learn Python Programming  /  Data Structures  /  Set

Set

A set is an unordered collection of unique values — the natural tool whenever you need to remove duplicates or compare two groups of items mathematically.

Creating a Set

R Code
fruits = {"apple", "banana", "mango", "apple"}  # duplicate "apple" is dropped
print(fruits)

# the fastest way to remove duplicates from a list
nums = [1, 2, 2, 3, 3, 3, 4]
unique_nums = set(nums)
print(unique_nums)
Output
{'banana', 'mango', 'apple'}
{1, 2, 3, 4}
💡 Tip
Sets have no guaranteed order, so the printed order of elements may differ from the order you added them - never rely on a set staying in a particular order.

Adding and Removing Elements

R Code
fruits = {"apple", "banana"}

fruits.add("mango")
fruits.discard("banana")   # does nothing if the item is missing (no error)
print(fruits)
Output
{'mango', 'apple'}

Set Operations

R Code
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)   # union: everything in either set
print(a & b)   # intersection: only what is in both
print(a - b)   # difference: in a but not in b
print(a ^ b)   # symmetric difference: in either, but not both
Output
{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{1, 2, 5, 6}

Advanced: Checking Overlap Between Two Groups

🚀 Advanced Example
Set operations are a fast, readable way to compare two groups of participants in a research context - for example, students who took both of two optional courses.
R Code
course_a_students = {"Rafi", "Meera", "Zayn", "Nadia"}
course_b_students = {"Meera", "Zayn", "Farid"}

took_both = course_a_students & course_b_students
only_a = course_a_students - course_b_students

print("Took both:", took_both)
print("Only course A:", only_a)
Output
Took both: {'Meera', 'Zayn'}
Only course A: {'Rafi', 'Nadia'}

Key Points

  • A set holds only unique values and has no guaranteed order.
  • set(some_list) is the fastest way to remove duplicates.
  • Union (|), intersection (&), difference (-), and symmetric difference (^) compare two sets directly.
  • Sets are ideal for comparing group membership, like overlapping survey respondents.