Tutorials Logic, IN info@tutorialslogic.com

Sets in Python Set Operations Methods

Set Basics

A set stores unique values and ignores duplicates automatically.

Use sets when membership checks, duplicate removal, or mathematical set operations are more important than order.

Sets are powerful for comparisons: what two groups share, what one group has that another does not, and whether a value has already been seen.

Python Set

A set is an unordered collection of unique items. Sets automatically remove duplicates and are highly optimized for membership testing.

  • Unordered - no guaranteed order
  • Unique items only - duplicates are removed
  • Mutable - you can add/remove items
  • O(1) average lookup - very fast membership test
  • No indexing or slicing

Creating Sets

Build Sets Without Duplicates

Build Sets Without Duplicates
empty = set()           # NOT {} - that creates an empty dict!
fruits = {"apple", "banana", "mango"}
nums = {1, 2, 3, 2, 1}  # duplicates removed
print(nums)             # {1, 2, 3}

# From other iterables
from_list = set([1, 2, 2, 3, 3, 4])
from_str  = set("hello")   # {'h', 'e', 'l', 'o'}
from_range = set(range(5)) # {0, 1, 2, 3, 4}

print(type(fruits))  # <class 'set'>
print(len(fruits))   # 3

Add and Remove Items

Modifying Sets

Modifying Sets
fruits = {"apple", "banana", "mango"}

# Add
fruits.add("orange")
fruits.update(["grape", "kiwi"])  # add multiple

# Remove
fruits.remove("banana")    # raises KeyError if not found
fruits.discard("papaya")   # safe - no error if not found
popped = fruits.pop()      # removes and returns a random item
fruits.clear()             # removes all items

# Check membership
colors = {"red", "green", "blue"}
print("red" in colors)     # True
print("yellow" in colors)  # False

Set Operations

Sets support mathematical operations like union, intersection, and difference.

Combine and Compare Sets

Combine and Compare Sets
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}

# Union - all items from both sets
print(a | b)           # {1, 2, 3, 4, 5, 6, 7, 8}
print(a.union(b))      # same

# Intersection - items in both sets
print(a & b)                  # {4, 5}
print(a.intersection(b))      # same

# Difference - items in a but not b
print(a - b)                  # {1, 2, 3}
print(a.difference(b))        # same

# Symmetric difference - items in either but not both
print(a ^ b)                          # {1, 2, 3, 6, 7, 8}
print(a.symmetric_difference(b))      # same

# Subset and superset
x = {1, 2}
print(x.issubset(a))    # True  - all of x is in a
print(a.issuperset(x))  # True  - a contains all of x
print(a.isdisjoint({9, 10}))  # True - no common items

Set Methods Reference

Method Description
add(x) Add element x
update(iterable) Add multiple elements
remove(x) Remove x (KeyError if missing)
discard(x) Remove x (no error if missing)
pop() Remove and return a random element
clear() Remove all elements
union(s) Return union of sets
intersection(s) Return common elements
difference(s) Return elements not in s
symmetric_difference(s) Return elements in either but not both
issubset(s) True if all elements are in s
issuperset(s) True if s is a subset
isdisjoint(s) True if no common elements
copy() Return a shallow copy

frozenset

Create an Immutable Set

Create an Immutable Set
# frozenset is immutable - can be used as dict key
fs = frozenset([1, 2, 3])
print(fs)  # frozenset({1, 2, 3})

# Can be used as a dict key (regular set cannot)
lookup = {frozenset([1, 2]): "pair", frozenset([3]): "single"}

# Practical: remove duplicates from a list while preserving order
def unique(lst):
    seen = set()
    return [x for x in lst if not (x in seen or seen.add(x))]

data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
print(unique(data))  # [3, 1, 4, 5, 9, 2, 6]
Set operation check

Can You Manage Unique Values?

4 checks
  • Set Methods Reference includes Add element x, Add multiple elements, Remove x (KeyError if missing), and Remove x (no error if missing).
  • A set is an unordered collection of unique items.
  • Sets automatically remove duplicates and are highly optimized for membership testing.
  • Union, intersection, difference, and symmetric difference express relationships between groups.

Set Decisions

0 of 2 checked

Q1. What is the main beginner use of a set?

Q2. Which method is safe when the value may be missing?

Set Results That Surprise Beginners

  • Expecting order from a set

    Use a list when order matters. Use sorted(set_value) when you need ordered output.
  • Using unhashable items

    Store immutable values such as strings, numbers, or tuples, not lists or dictionaries.
  • Removing missing values with remove()

    Use discard() when missing values are acceptable.

Try this next

Clean Unique Values

0 of 3 completed

  1. Turn a list of repeated emails into unique emails.
  2. Use set intersection to find students in two clubs.
  3. Test remove and discard with a missing value and explain the difference.

Set Operations

Do not rely on set order. Use a list if order matters, and use a set when uniqueness or membership checks matter more.

No. Set items must be hashable. Use tuples for fixed grouped values, or store an ID instead of a mutable object.

Checking membership and removing duplicates. For example, keep a seen set while processing names or IDs.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.