Python Sets Explained: A Beginner’s Guide to Unique & Unordered Data

When working with Python, we often deal with collections of data. Sometimes we want lists that preserve order, sometimes tuples that remain unchanged. But what if we want to store data without duplicates and perform quick operations like union or intersection? That’s where sets come in.

In this article, we’ll explore what sets are, how to use them, and why they are so useful in Python programming.


🔹 What is a Set in Python?

A set is an unordered collection of unique elements.

  • Unordered → The items do not have an index or a fixed position like lists or tuples.

  • Unique → Duplicate elements are automatically removed.

Think of a set as a mathematical set — it either contains an element or it doesn’t.

Example:

# Creating a set
my_set = {1, 2, 3, 4, 4, 2}

print(my_set)  
# Output: {1, 2, 3, 4}  → duplicates are removed automatically

🔹 Creating Sets

You can create a set in two ways:

Way - 1:

# Using curly braces
numbers = {1, 2, 3, 4, 1}
print(numbers)
#output - {1, 2, 3, 4}

Way - 2:

# Using set() constructor
letters = set(["a", "b", "c", "a"])
print(letters)  
# Output: {'a', 'b', 'c'}

👉 Notice how duplicates vanish!

⚠️ Important: While initiating an empty set it must be created using set() and not {}, because {} creates an empty dictionary. You can see it practically below:

empty_set = set()
empty_dict = {}
print(type(empty_set))  # <class 'set'>
print(type(empty_dict)) # <class 'dict'>

🔹 Accessing Set Elements

Since sets are unordered, you can’t access elements using an index. But you can:

  • Loop through a set

    ```python fruits = {"apple", "banana", "cherry"}

    Looping

    for f in fruits: print(f)

'''output - banana apple cherry '''


    Since sets are unordered, we will get different outputs every time we run the code.

* **Check membership** using `in`


```python
# Membership check
print("apple" in fruits)   # output - True
print("grape" in fruits)   # output - False

🔹 Adding and Removing Elements

Sets are mutable, so we can add or remove elements.

# Add an element
fruits.add("mango")
print(fruits)

# Add multiple elements
fruits.update(["kiwi", "orange"])
print(fruits)

# Remove elements
# If we try to remove an element that is not present the remove function will give an error
# and the discard method will not produce any error.
fruits.remove("apple")   # Error if not found
fruits.discard("grape")  # No error if not found
print(fruits)

# Pop removes a random element
removed = fruits.pop()
print("Removed:", removed)

🔹 Set Operations (Like in Math!)

One of the coolest things about sets is that they support mathematical set operations:

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

print(A | B)  # Union(Adds the elements of set A and B) → {1, 2, 3, 4, 5, 6}
print(A & B)  # Intersection(Common elements in both sets) → {3, 4}
print(A - B)  # Difference(Elements present in set A that are not present in set B) → {1, 2}
print(B - A)  # Difference(Elements present in set B that are not present in set A) → {3, 4}
print(A ^ B)  # Symmetric Difference(Unique elements in both the sets) → {1, 2, 5, 6}

🔹 Why Use Sets?

Sets are super useful when:
✅ You want to remove duplicates from a collection
✅ You need fast membership testing (in is much faster in sets than in lists)
✅ You want to perform mathematical operations like union, intersection, and difference

Example: Removing duplicates from a list

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)  # [1, 2, 3, 4, 5]

🔹 Frozen Sets (Immutable Sets)

Sometimes you need an immutable set (cannot be changed). That’s where frozenset() comes in. Once a frozenset is created we can not manipulate any elements.

fs = frozenset([1, 2, 3, 4])
print(fs)

# fs.add(5)  ❌ Error → frozenset object has no attribute 'add'

🔹 Conclusion

Python Sets are a powerful and flexible data structure. They:

  • Ensure uniqueness of elements

  • Allow fast membership checks

  • Support mathematical set operations

  • Have a special immutable version called frozenset

Next time you need to handle unique and unordered data, reach for sets! 🚀


📝 PRACTICE

Now it’s time to test what you’ve learned about sets! Try solving the following tasks:

  1. Create a set of your 5 favorite fruits.

    • Add a new fruit to the set.

    • Remove one fruit using discard().

    • Try removing a fruit that does not exist and observe what happens.

  2. Create two sets:

    • A = {1, 2, 3, 4, 5}

    • B = {4, 5, 6, 7, 8}
      Perform the following:

    • Union

    • Intersection

    • Difference (A - B and B - A)

    • Symmetric Difference

  3. Remove duplicates from this list using a set:

     nums = [10, 20, 10, 30, 40, 20, 50, 30]
    
  4. Create a frozen set using numbers from 1–5.

    • Try to add a number to it and see what happens.
  5. You have two lists of students:

     math_students = ["Alice", "Bob", "Charlie", "David"]
     science_students = ["Charlie", "David", "Eva", "Frank"]
    
    • Find students who are enrolled in both subjects.

    • Find students who are enrolled in only Math but not Science.

    • Find students who are in at least one subject.

0
Subscribe to my newsletter

Read articles from Tammana Prajitha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tammana Prajitha
Tammana Prajitha