Tutorials Logic
Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Sets in Python — Set Operations and Methods

What is a 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

Creating Sets
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

Adding & Removing Items

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 (Math)

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

Set Operations
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

MethodDescription
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 - Immutable Set

frozenset
# 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]

Ready to Level Up Your Skills?

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