Python Sets: The Simplest Truths in Life, Only Once

For those who write Python, you will eventually encounter something that seems inconspicuous — sets. When you first come across it, you might think it’s not very useful, similar to a list. But once you truly understand it, you will find that it is not just a tool; it actually hides a certain “wisdom of life” behind it.

Today, let’s talk about Python sets, explaining their characteristics, usage, and philosophy in the simplest way possible.

Python Sets: The Simplest Truths in Life, Only Once

01 What is a Set?

For example, when you go to a night market to buy fruits, the vendor grabs a big bag of mixed oranges, apples, and bananas for you. When you get home and count:

  • There are 5 oranges
  • 3 apples
  • 2 bananas

If this were a list, it would faithfully remember every single fruit you bought:

fruits = ["orange", "orange", "orange", "orange", "orange", "apple", "apple", "apple", "banana", "banana"]

But if it were a set, the situation would change. A set only cares about “what fruits you bought” and does not care about how many:

fruits = {"orange", "apple", "banana"}

Key Point 1: A set contains no duplicate elements. No matter how many “oranges” you put in, it will only keep one.

Another characteristic: the items in a set are unordered. When you look at it, today it might be <span>{"banana", "orange", "apple"}</span>, and tomorrow it might be <span>{"apple", "banana", "orange"}</span>, with no guarantee of order.

This is like life: you may have many friends, but there are only a few true confidants, and it doesn’t matter who you meet first or last.

02 How to Create a Set?

There are two ways:

1. Using curly braces <span>{}</span>

my_set = {1, 2, 3, "hello"}
print(my_set)
# Output: {1, 2, 3, 'hello'}

2. Using the <span>set()</span> function

This method is especially handy when you have a bunch of duplicate data.

numbers = [1, 2, 2, 3, 4, 4, 4]
unique = set(numbers)
print(unique)  
# Output: {1, 2, 3, 4}

Note! An empty set cannot be written as <span>{}</span>, because that is a dictionary. You should write <span>set()</span>.

empty = set()
print(empty)  # Output: set()

03 What Can a Set Contain?

The elements of a set must be immutable.

  • Can include: integers, floats, strings, tuples
  • Cannot include: lists, dictionaries, another set

For example:

ok_set = {1, 3.14, "hello", (1, 2)}
# ✅ Valid

But if you write:

bad_set = {[1, 2], {"a": 1}}
# ❌ Error

Because lists and dictionaries are mutable, which makes it impossible to determine uniqueness.

04 Common Set Operations

Adding Elements

fruits = {"apple", "banana"}
fruits.add("orange")
print(fruits)
# Output: {'apple', 'banana', 'orange'}

Removing Elements

numbers = {1, 2, 3, 4, 5}
numbers.remove(3)   # Raises an error if the element does not exist
numbers.discard(10) # Does not raise an error if it does not exist
print(numbers)

Randomly Remove One

n = {1, 2, 3}
x = n.pop()
print(x)   # Randomly pops one

Check Membership

vowels = {'a', 'e', 'i', 'o', 'u'}
print('a' in vowels)  # True
print('x' in vowels)  # False

05 Mathematical Operations

The coolest part about sets is that they inherently support mathematical set operations.

Union

Combining two sets, automatically removing duplicates:

A = {1, 2, 3}
B = {3, 4, 5}
print(A | B)         # {1, 2, 3, 4, 5}
print(A.union(B))    # {1, 2, 3, 4, 5}

Intersection

Finding common elements:

print(A & B)          # {3}
print(A.intersection(B))

Difference

Finding elements in one set that are not in the other:

print(A - B)          # {1, 2}
print(B - A)          # {4, 5}

Symmetric Difference

The non-overlapping parts of two sets:

print(A ^ B)          # {1, 2, 4, 5}

Isn’t it intuitive? You can completely treat Python as a little helper for math class.

06 Practical Uses in Life

Scenario 1: Quick Deduplication

For example, you have a list of names, and there are many duplicates.

names = ["Zhang San", "Li Si", "Wang Wu", "Zhang San", "Li Si"]
unique_names = list(set(names))
print(unique_names)   # ['Zhang San', 'Li Si', 'Wang Wu']

Scenario 2: Finding Intersection

For example, you have two lists:

  • Those who signed up for the basketball club
  • Those who signed up for the football club

To find out who “signed up for both”, just one line of code:

basketball = {"Zhang San", "Li Si", "Wang Wu"}
football = {"Wang Wu", "Zhao Liu", "Zhang San"}
print(basketball & football)  # {'Zhang San', 'Wang Wu'}

Scenario 3: Difference

For example, to find out who only signed up for basketball and not for football:

print(basketball - football)  # {'Li Si'}

This is the power of sets.

07 A Philosophical Angle

At this point, you might think that sets are just a tool for deduplication. But upon closer inspection, Python’s sets actually hide a bit of wisdom about life:

  • Uniqueness: Truly important things do not repeat. No matter how many friends you have, there is only one confidant.
  • Unorderedness: Life has no fixed script; the order in which you meet people is not that important. What matters is who ultimately remains in your set.
  • Simple Rules: As long as you remember the two rules of “immutability” and “uniqueness”, the rest of the world will be orderly.

After writing code for a long time, you will find that some data structures are metaphors for life. Lists represent trivialities, dictionaries represent networks of relationships, while sets represent minimalism and cleanliness.

Conclusion

In this article, we started with a little story about “buying fruits” to clarify Python’s sets:

  • They are unique and unordered
  • They have various efficient operations (add, remove, search, modify)
  • They inherently support mathematical set operations
  • They are super practical in scenarios like deduplication and finding intersections

More importantly, sets remind us: Don’t let life be filled with too many duplicate garbage elements; just keep the “unique things”.

Leave a Comment