Sets

Python - A Quick Start for existing Programers

2 min read

Published Sep 16 2025, updated Sep 30 2025


21
0
0
0

Python

A set is a built-in unordered, mutable collection of unique elements.

  • Think of it like a mathematical set.
  • Duplicates are automatically removed.
  • Sets are mutable, but elements must be hashable (immutable types) like numbers, strings, or tuples of immutables.

Examples:

empty = set()
# empty set, note: {} creates an empty dictionary, not a set

s1 = {1, 2, 3}
# set literal

Sets don't support accessing by an index value, you only have the option to see if a value is in a set:

s = {1, 2, 3}

print(2 in s)
# True

print(5 not in s)
# True




Built-in Functions for Sets

The following built in functions work with sets:

  • len(s) → number of elements in the set
  • min(s) → smallest element (if ordering is defined)
  • max(s) → largest element
  • sum(s) → sum of elements (only works if numeric)
  • sorted(s) → returns a new list of elements in sorted order
  • any(s)True if any element is truthy
  • all(s)True if all elements are truthy

Examples:

s = {3, 1, 0, 5}

print("len(s):", len(s))
# 4
print("min(s):", min(s))
# 0
print("max(s):", max(s))
# 5
print("sum(s):", sum(s))
# 9
print("sorted(s):", sorted(s))
# [0, 1, 3, 5]

print("any(s):", any(s))
# True (0 is falsy, but others are truthy)
print("all(s):", all(s))
# False (because of 0)





Modifying sets

Function

Description

s.add(elem)

Add a single element to the set

s.update(*iterables)

Add multiple elements from one or more iterables

s.remove(elem)

Remove element; raises KeyError if not present

s.discard(elem)

Remove element if present; no error if missing

s.pop()

Remove and return an arbitrary element

s.clear()

Remove all elements from the set


Examples:

s = {1, 2, 3}

s.add(4)
# {1, 2, 3, 4}

s.update([5, 6])
# {1, 2, 3, 4, 5, 6}

s.remove(3)
# removes 3 (error if not found)

s.discard(10)
# safe remove (no error if not found)

val = s.pop()
# removes & returns an arbitrary element

s.clear()
# empty set





Set Operations and relations

Sets allow you to compare the contents of two sets, to show the similarities or differences between the two sets.


Python Set Operations


Examples of operations (all these methods have a shorthand version too using |, &, -, ^):

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

# union
print(a.union(b))
# or short hand version
print(a | b)
# {1,2,3,4,5,6}

# intersection
print(a.intersection(b))
# or short hand version
print(a & b)
# {3,4}

# difference
print(a.difference(b))
# or short hand version
print(a - b)
# {1,2}

# symmetric difference
print(a.symmetric_difference(b))
# or short hand version
print(a ^ b)
# {1,2,5,6}

Examples of relations:

a = {1, 2}
b = {1, 2, 3}

print(a <= b)
# subset → True

print(b >= a)
# superset → True

print(a.issubset(b))
# True

print(b.issuperset(a))
# True

# no elements in common
print(a.isdisjoint({4, 5}))
# True

# Check equality of sets (same elements, order doesn’t matter)
{1, 2, 3} == {3, 2, 1}
# True



Casting to a set

Convert an iterable into a set to remove duplicates and allow set operations, works with:

  • List
  • Tuple
  • String
  • Dictionary - keys only

Examples:

# List
set([1, 2, 2, 3])
# {1, 2, 3}

# Tuple
set((1, 1, 2))
# {1, 2}

# String
set("hello")
# {'h', 'e', 'l', 'o'}

# Dictionary
set({'a':1, 'b':2})
# {'a', 'b'}



Set Comprehension

  • Syntax is almost the same as list comprehension, but with {} instead of [].
  • Produces a set → unordered, unique elements, no duplicates.
  • Useful for deduplication, filtering, and transformations where order doesn’t matter.
  • Order is not guaranteed.

Syntax:

{expression for item in iterable if condition}


Examples:

nums = [1, 2, 2, 3, 4, 4, 5]

# ----------------------------------------
# Basic transformation
squares = {x**2 for x in nums}
print("Squares set:", squares) # {1, 4, 9, 16, 25}

# ----------------------------------------
# Filtering values
evens = {x for x in nums if x % 2 == 0}
print("Even numbers set:", evens)

# ----------------------------------------
# Deduplication (automatically handled)
duplicates_removed = {x for x in nums}
print("Deduped set:", duplicates_removed)

# ----------------------------------------
# Strings with set comprehension
word = "comprehension"
unique_chars = {ch for ch in word}
print("Unique chars:", unique_chars)

# Uppercase vowels only
vowels_upper = {ch.upper() for ch in word if ch in "aeiou"}
print("Uppercase vowels:", vowels_upper)

# ----------------------------------------
# Conditional expression inside comprehension
labels = {("even" if x % 2 == 0 else "odd") for x in nums}
print("Even/Odd labels set:", labels)

# ----------------------------------------
# Nested set comprehension
pairs = {(x, y) for x in [1, 2] for y in [3, 4]}
print("Cartesian product pairs:", pairs)

# ----------------------------------------
# Using functions
def cube(x): return x**3
cubes = {cube(x) for x in nums}
print("Cubes set:", cubes)

# ----------------------------------------
# Real-world example: normalize text
text = "The quick brown fox jumps over the lazy dog"
unique_words = {word.lower() for word in text.split()}
print("Unique words (lowercased):", unique_words)




Full demonstration of sets

# 1. Creating sets
a = {1, 2, 3, 4}
b = set([3, 4, 5, 6])
c = set((4, 5, 6, 7))
s = set("hello")
d = set({'x': 1, 'y': 2})

print("Sets:", a, b, c, s, d)

# 2. Set operations
print("\n# Set Operations")
print("Union:", a.union(b))
# a | b
print("Intersection:", a.intersection(b))
# a & b
print("Difference:", a.difference(b))
# a - b
print("Symmetric Difference:", a.symmetric_difference(b))
# a ^ b

# 3. Set methods
print("\n# Set Methods")
a.add(10)
print("After add(10):", a)
a.update([20, 30])
print("After update([20,30]):", a)
a.discard(2)
print("After discard(2):", a)
# a.remove(100) # would raise KeyError if uncommented
popped = a.pop()
print("After pop():", a, "Popped element:", popped)
copy_a = a.copy()
print("Copy of a:", copy_a)
a.clear()
print("After clear():", a)

# 4. Set casting (removing duplicates)
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = list(set(lst))
print("\nCasting to set (remove duplicates):", unique_lst)

# 5. Set comparisons
x = {1, 2, 3}
y = {1, 2, 3, 4, 5}
z = {6, 7}

print("\n# Set Comparisons")
print("x <= y (subset):", x <= y)
print("x < y (proper subset):", x < y)
print("y >= x (superset):", y >= x)
print("y > x (proper superset):", y > x)
print("x.isdisjoint(z):", x.isdisjoint(z))
print("{1,2,3} == {3,2,1}:", {1,2,3} == {3,2,1})

Products from our shop

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Mug

Docker Cheat Sheet Mug

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Mug

Vim Cheat Sheet Mug

SimpleSteps.guide branded Travel Mug

SimpleSteps.guide branded Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - Black

Developer Excuse Javascript Mug - Black

SimpleSteps.guide branded stainless steel water bottle

SimpleSteps.guide branded stainless steel water bottle

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Dark

Developer Excuse Javascript Hoodie - Dark

© 2025 SimpleSteps.guide
AboutFAQPoliciesContact