DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python Sets Explained Simply (Unique and Unordered Collections)

Sets are collections that store unique items with no duplicates. They are useful for membership testing and removing duplicates quickly.

What is a set?

A set is created with curly braces {} and items separated by commas. Order does not matter.

fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}
mixed = {10, "hello", True}
Enter fullscreen mode Exit fullscreen mode

You can also create a set from a list:

unique_numbers = set([1, 2, 2, 3, 3, 3])
print(unique_numbers)  # {1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

An empty set (note: {} makes a dictionary):

empty_set = set()
Enter fullscreen mode Exit fullscreen mode

Sets automatically remove duplicates.

Adding and removing items

Add an item with add():

fruits.add("orange")
print(fruits)  # Includes orange
Enter fullscreen mode Exit fullscreen mode

Remove an item with remove() (raises error if not found) or discard() (no error):

fruits.remove("banana")
fruits.discard("missing")  # No error
Enter fullscreen mode Exit fullscreen mode

Common operations

Check membership:

print("apple" in fruits)  # True or False
Enter fullscreen mode Exit fullscreen mode

Get length:

print(len(fruits))  # Number of unique items
Enter fullscreen mode Exit fullscreen mode

Loop over a set:

for fruit in fruits:
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

Set operations

Union (all items):

set1 = {1, 2, 3}
set2 = {3, 4, 5}
combined = set1.union(set2)  # or set1 | set2
print(combined)  # {1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode

Intersection (common items):

common = set1.intersection(set2)  # or set1 & set2
print(common)  # {3}
Enter fullscreen mode Exit fullscreen mode

Difference (items in one but not both):

diff = set1.difference(set2)  # or set1 - set2
print(diff)  # {1, 2}
Enter fullscreen mode Exit fullscreen mode

Simple examples

Remove duplicates from a list:

scores = [85, 92, 85, 78, 92]
unique_scores = set(scores)
print(unique_scores)  # {85, 92, 78}
Enter fullscreen mode Exit fullscreen mode

Check common friends:

friends_a = {"Ali", "Sara", "Reza"}
friends_b = {"Sara", "Mohammad", "Reza"}
common = friends_a & friends_b
print(common)  # {"Sara", "Reza"}
Enter fullscreen mode Exit fullscreen mode

Important notes

  • Sets are unordered: items have no index.
  • Sets are mutable, but items must be immutable (no lists inside sets).
  • Sets are fast for checking if an item exists.

Quick summary

  • Create sets with curly braces or set().
  • Sets store unique items only.
  • Use add(), remove(), and discard() to modify.
  • Perform union, intersection, and difference easily.
  • Ideal for removing duplicates and membership tests.

Practice using sets for unique collections. They provide efficient operations not available with lists in Python programs.

Top comments (0)