Sets

Python - A Quick Start for existing Programers

2 min read

Published Sep 16 2025, updated Aug 17 2026


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))       # 4print("min(s):", min(s))       # 0print("max(s):", max(s))       # 5print("sum(s):", sum(s))       # 9print("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}​# unionprint(a.union(b)) # or short hand versionprint(a | b)   # {1,2,3,4,5,6}​# intersectionprint(a.intersection(b))# or short hand versionprint(a & b)   # {3,4}​# differenceprint(a.difference(b))# or short hand versionprint(a - b)   # {1,2}​# symmetric differenceprint(a.symmetric_difference(b))# or short hand versionprint(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 commonprint(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:

# Listset([1, 2, 2, 3])  # {1, 2, 3}​# Tupleset((1, 1, 2))  # {1, 2}​# Stringset("hello")  # {'h', 'e', 'l', 'o'}​# Dictionaryset({'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 transformationsquares = {x**2 for x in nums}print("Squares set:", squares)  # {1, 4, 9, 16, 25}​# ----------------------------------------# Filtering valuesevens = {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 comprehensionword = "comprehension"unique_chars = {ch for ch in word}print("Unique chars:", unique_chars)​# Uppercase vowels onlyvowels_upper = {ch.upper() for ch in word if ch in "aeiou"}print("Uppercase vowels:", vowels_upper)​# ----------------------------------------# Conditional expression inside comprehensionlabels = {("even" if x % 2 == 0 else "odd") for x in nums}print("Even/Odd labels set:", labels)​# ----------------------------------------# Nested set comprehensionpairs = {(x, y) for x in [1, 2] for y in [3, 4]}print("Cartesian product pairs:", pairs)​# ----------------------------------------# Using functionsdef cube(x): return x**3cubes = {cube(x) for x in nums}print("Cubes set:", cubes)​# ----------------------------------------# Real-world example: normalize texttext = "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 setsa = {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 operationsprint("\n# Set Operations")print("Union:", a.union(b))                   # a | bprint("Intersection:", a.intersection(b))     # a & bprint("Difference:", a.difference(b))         # a - bprint("Symmetric Difference:", a.symmetric_difference(b))  # a ^ b​# 3. Set methodsprint("\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 uncommentedpopped = 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 comparisonsx = {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})
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact