Python Set

Learn Python sets with simple examples. See how to create a set, add and remove items, check membership, remove duplicates, and use union, intersection, difference, symmetric difference, issubset, issuperset, and frozenset.

Published

Updated

Read time 7 min read

Reviewed byDeepak Prasad

Python Set

A set in Python is an unordered collection of unique items. Sets are useful when you want to remove duplicates, check membership quickly, or perform mathematical set operations such as union, intersection, difference, and symmetric difference.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Python set quick reference

Task Use
Create a set my_set = {1, 2, 3}
Create an empty set my_set = set()
Convert list to set set(my_list)
Add one item my_set.add(item)
Add multiple items my_set.update(items)
Check membership item in my_set
Remove item and raise error if missing my_set.remove(item)
Remove item safely my_set.discard(item)
Remove arbitrary item my_set.pop()
Remove all items my_set.clear()
Union a | b or a.union(b)
Intersection a & b or a.intersection(b)
Difference a - b or a.difference(b)
Symmetric difference a ^ b or a.symmetric_difference(b)
Check subset a.issubset(b) or a <= b
Check superset a.issuperset(b) or a >= b

What is a set in Python?

  • A set is a collection of unique items.
  • It is unordered—display order is not guaranteed.
  • It is mutable—you can add and remove items.
  • It can contain only hashable items (no lists or dicts as elements).
  • Duplicate values are removed automatically.
  • You cannot access set items by index.

Sets are useful for uniqueness, membership testing, and set operations. See list vs set vs tuple vs dictionary for a broader comparison.


Create a set in Python

Non-empty set with curly braces:

python
tags = {"python", "set", "tutorial"}
print(tags)
Output

Empty set with set():

python
empty = set()
print(empty)
print(type(empty))
Output

Important: {} creates an empty dictionary, not an empty set.

Convert from other types:

python
numbers = set([1, 2, 2, 3, 3, 3])
letters = set("hello")
keys_only = set({"a": 1, "b": 2})
from_tuple = set((1, 2, 3))

print(numbers)
print(letters)
print(keys_only)
print(from_tuple)
Output

numbers becomes {1, 2, 3}. A string becomes individual characters. A dictionary conversion uses keys only.


Python set example

Duplicates are removed and order is not fixed:

python
colors = {"red", "blue", "green", "red", "blue"}
print(colors)
print(len(colors))

scores = [10, 20, 20, 30, 10]
unique_scores = set(scores)
print(unique_scores)
Output

You see three unique colors and three unique scores; the printed order may vary between runs.


Add items to a Python set

One item with add():

python
fruits = {"apple", "mango"}
fruits.add("grape")
fruits.add("apple")
print(fruits)
Output

"apple" is not duplicated.

Multiple items with update():

python
fruits = {"apple", "mango"}
fruits.update(["grape", "banana"])
fruits.update({"kiwi", "apple"})
print(fruits)
Output

update() accepts lists, tuples, strings, or another set.


Access or loop through set items

Sets are iterable, but not indexable:

python
tags = {"python", "set", "data"}

for tag in tags:
    print(tag)
Output

Use in to test membership—you cannot use tags[0].


Check if an item exists in a set

python
allowed = {"admin", "editor", "viewer"}
selected = {"python", "set", "tutorial"}

print("admin" in allowed)
print("guest" in allowed)
print("python" in selected)
print("java" in selected)
Output

Membership checks are one of the main reasons to use sets—for usernames, tags, or allowed IDs.


Remove items from a Python set

Method Missing item behavior
remove() Raises KeyError
discard() No error
pop() Raises KeyError only if set is empty
clear() Removes all items
python
items = {"ab", "dc", "cd"}

items.discard("missing")
print(items)

items.remove("dc")
print(items)

removed = items.pop()
print(removed)
print(items)

items.clear()
print(items)
Output

pop() removes an arbitrary item—not the “first” item, because sets are unordered.

python
items = {"x", "y"}

try:
    items.remove("z")
except KeyError as e:
    print(e)
Output

remove("z") raises KeyError.


Python set operations

Operation Meaning Method Operator
Union Items in either set a.union(b) a | b
Intersection Items in both sets a.intersection(b) a & b
Difference Items in a but not b a.difference(b) a - b
Symmetric difference Items in either set, but not both a.symmetric_difference(b) a ^ b

Python's set documentation lists these methods and operator forms for set and frozenset.

python
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A | B)
print(A & B)
print(A - B)
print(B - A)
print(A ^ B)
Output

Python set union

Union combines unique items from both sets and returns a new set:

python
tags_a = {"python", "linux", "cloud"}
tags_b = {"python", "docker", "cloud"}

combined = tags_a.union(tags_b)
print(combined)
print(tags_a | tags_b)
Output

Use union to merge categories, IDs, or tags without duplicates.


Python set intersection

Intersection returns only common items. For method details and operator forms, see Python set intersection.

python
group_a = {101, 102, 103, 104}
group_b = {103, 104, 105, 106}

shared = group_a & group_b
print(shared)
Output

Output is {103, 104}—users or tags present in both collections.


Python set difference

Difference is one-sided—items in the first set that are not in the second:

python
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A - B)
print(B - A)
Output

You get {1, 2} and {5, 6}. A - B is not the same as B - A. See Python set difference for more examples.


Python set symmetric difference

Symmetric difference returns items in either set, but not both:

python
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A.symmetric_difference(B))
print(A ^ B)
Output

Both produce {1, 2, 5, 6}. For more detail, see Python symmetric difference.


Python issubset()

issubset() returns True when all items in one set are in another:

python
required = {"email", "password"}
submitted = {"email", "password", "remember_me"}

print(required.issubset(submitted))
print(submitted.issubset(required))
print(required <= submitted)
Output

The first and third checks are True; the second is False.


issubset() vs issuperset() vs isdisjoint()

Method Meaning
a.issubset(b) All items in a are also in b
a.issuperset(b) a contains all items of b
a.isdisjoint(b) a and b have no common items
python
a = {1, 2, 3}
b = {1, 2, 3, 4, 5}
c = {6, 7}

print(a.issubset(b))
print(b.issuperset(a))
print(a.isdisjoint(c))
Output

Results are True, True, and True.


Set vs list vs tuple vs dictionary

Feature Set List Tuple Dictionary
Unique items Yes No No Keys are unique
Ordered No Yes Yes Yes (insertion order)
Mutable Yes Yes No Yes
Index access No Yes Yes Key-based
Main use Unique items and set operations Ordered changeable collection Fixed ordered values Key-value lookup

Use a set when duplicates or fast membership matter more than order.


Frozenset in Python

frozenset is an immutable set:

python
frozen = frozenset([1, 2, 3, 2])
print(frozen)

lookup = {frozenset({"a", "b"}): "group-a"}
print(lookup[frozenset({"b", "a"})])
Output

You cannot add or remove items after creation. A frozenset can be a dictionary key or an element inside another set when all items are hashable.


When should you use a set?

  • Remove duplicates from a list: list(set(items)) — lists keep order and duplicates; see Python list when those matter.
  • Check membership quickly with in
  • Compare two collections for shared or unique values
  • Track unique visitors, tags, or IDs
  • Run union, intersection, difference, or symmetric difference

Avoid sets when you need duplicate values or a stable order.


Common mistakes with Python sets

  1. Using {} for an empty set — it creates a dict; use set().
  2. Expecting fixed display order — sets are unordered.
  3. Indexing a setmy_set[0] is invalid.
  4. Adding lists or dicts as elements — only hashable items are allowed.
  5. Confusing remove() and discard() — only remove() errors when missing.
  6. Thinking pop() removes the first item — it removes an arbitrary item.
  7. Forgetting duplicates are removed{1, 1, 2} is {1, 2}.
  8. Using sets when order or duplicates matter — use a list instead.
  9. Assuming set operations preserve list order — convert back with sorted() if needed.

Summary

A Python set stores unique, unordered items. Use {} for non-empty sets and set() for an empty set. Modify sets with add(), update(), remove(), discard(), and clear(). Compare collections with union, intersection, difference, and symmetric difference. Check relationships with issubset(), issuperset(), and isdisjoint().

Useful references


Frequently Asked Questions

1. What is a set in Python?

A set is an unordered collection of unique items. Duplicates are removed automatically, and you cannot access items by index.

2. How do you create an empty set in Python?

Use set(). Empty curly braces {} create an empty dictionary, not an empty set.

3. What is the difference between remove() and discard() in Python sets?

remove() raises KeyError if the item is missing. discard() does nothing when the item is not found.

4. How do you remove duplicates from a list in Python?

Convert the list to a set with set(my_list), then back to a list with list() if you need a list. Sets keep only unique values.

5. What is the difference between a set and a frozenset?

A set is mutable—you can add and remove items. A frozenset is immutable and can be used as a dictionary key or nested inside another set when hashable.

6. What is issubset() in Python?

a.issubset(b) returns True when every item in a is also in b. The operator shortcut is a <= b.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …