Tutorial

Python Set

Concise, original guide to python set: creation, methods (add/update/remove/discard), union/intersection/difference, set vs list, comprehension, and quick cheat sheet.

Drake Nguyen

Founder · System Architect

3 min read
Python Set
Python Set

Python set: overview

A python set is an unordered collection of unique, hashable elements. Sets are useful when you need to remove duplicates, test membership quickly, or perform classical set algebra (union, intersection, difference). Unlike lists and tuples, sets Netalith not preserve insertion order and cannot contain unhashable items such as lists or dictionaries.

How to create a set in Python

There are two common ways to create a set: using curly braces or the built-in set() constructor. Use curly braces only for non-empty sets; use set() to convert an iterable or to create an empty set.

# using braces (literal)
s1 = {1, 2, 3, 4, 2, 3}
print(s1)  # output: {1, 2, 3, 4}

# from an iterable (list, tuple, string)
items = [1, 2, 2, 3, 4]
s2 = set(items)
print(s2)  # output: {1, 2, 3, 4}

# empty set must use set()
empty = set()
print(type(empty))  # output: 

Python set methods: adding and updating elements

To add a single element, use add(). To merge multiple elements from any iterable (list, tuple, another set), use update(). Note the difference between update and add when adding several values.

s = set()
s.add(1)            # add single element
s.add(1)            # duplicates ignored
s.update([2, 3, 4]) # add multiple elements from iterable
s.update({5, 6})    # add elements from another set
print(s)            # output: {1, 2, 3, 4, 5, 6}

python set update vs add

Use add() for one element and update() to combine iterables. Both keep elements unique.

Removing elements: remove vs discard

To remove elements you can choose between remove() and discard(). remove() raises a KeyError if the element is absent; discard() does not.

nums = {1, 2, 3, 4}
nums.discard(3)  # safe if not present
nums.discard(3)  # still safe

nums.remove(2)   # removes 2
# nums.remove(2) # would raise KeyError if uncommented and 2 absent
print(nums)       # output: {1, 4}

Set operations with examples

Python implements standard set algebra methods: union(), intersection(), difference(), symmetric_difference(), and their operator counterparts (|, &, -, ^). These are useful for combining or comparing collections.

A = {1, 2, 3, 4}
B = {2, 3, 5, 7}

print("A | B ->", A.union(B))          # union
print("A & B ->", A.intersection(B))   # intersection
print("A - B ->", A.difference(B))     # elements in A not in B
print("B - A ->", B.difference(A))     # elements in B not in A
print("A ^ B ->", A.symmetric_difference(B))  # elements in either A or B but not both

python set union example, intersection example, difference example

Use union() or | to gather unique items from two sets. Use intersection() or & to find common elements. Use difference() or - to get items present in one set but not the other.

Set vs list vs tuple

Choose a set when you need fast membership tests and unique values. Lists preserve order and can contain duplicates; tuples are immutable ordered sequences. To deduplicate a list quickly, convert it to a set, then back to a list if order is not required.

python set comprehension

Set comprehensions create sets from expressions in a concise way, similar to list comprehensions:

squares = {x*x for x in range(6)}
print(squares)  # output: {0, 1, 4, 9, 16, 25}

Working with hashable and non-hashable elements

Only hashable objects (numbers, strings, tuples of hashable items, frozenset) can be members of a set. Mutable containers such as list or dict are not allowed. If you need an immutable set, use frozenset.

valid = {(1, 2), 'a', 3}
# invalid = {[1,2], {'x':1}}  # raises TypeError
f = frozenset([1,2,3])
print(type(f))  # 

Quick cheat sheet: common python set operations

  • create: {1,2} or set(iterable)
  • add one: add(elem)
  • add many: update(iterable)
  • remove safe: discard(elem)
  • remove raising: remove(elem)
  • union: union() or |
  • intersection: intersection() or &
  • difference: difference() or -
  • symmetric difference: symmetric_difference() or ^
  • comprehension: {expr for x in iterable}
Reference: For authoritative details and the full API, consult the official Python documentation on sets (built-in types and set methods).

These examples demonstrate how to create and manipulate a python set, remove duplicates from iterables, and perform set operations efficiently. For hands-on practice, try converting lists to sets, using set comprehensions, and comparing sets with lists and tuples in your own scripts.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.