Python Tutorial
Estimated reading: 4 minutes 277 views

Python Sets – Create, Modify, and Use Set Operations


Introduction – What Is a Set in Python?

A set in Python is an unordered, unindexed collection that stores only unique elements. It’s ideal for deduplication, fast membership tests, and performing set-theory operations like union, intersection, and difference.

Unlike lists or tuples, sets are mutable (can be changed) but do not allow duplicates or maintain order.


In this guide, you’ll learn:

  • How to create, access, and modify Python sets
  • Core set operations like union and intersection
  • Methods for copying, joining, and updating sets
  • Real-world applications with exercises

Topics Covered

Topic Description
Python Sets: Access / Add / RemoveCreating sets, adding/removing elements, and accessing items
Python Loop SetsIterating through sets
Python Copy / Join SetsDuplicating and combining sets
Python Set OperatorsUnion, intersection, difference, symmetric difference
Python Set MethodsBuilt-in methods for set manipulation
Python Set ExercisesPractice problems to test understanding

Creating Sets in Python

fruits = {"apple", "banana", "cherry"}
print(fruits)

Explanation:

  • Sets use {} or the set() constructor.
  • Duplicates are automatically removed.

Using set() Constructor

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

Converts any iterable (like list/tuple) into a set.


Accessing and Looping Through Sets

Loop through elements:

for fruit in fruits:
    print(fruit)

Sets are unordered, so the order may change with every execution.


Adding and Removing Elements

add() – Add a single item:

fruits.add("orange")

update() – Add multiple items:

fruits.update(["grape", "melon"])

remove() – Remove item, raises error if not found:

fruits.remove("banana")

discard() – Remove item safely:

fruits.discard("kiwi")

Set Operations – Algebraic Power

Union (| or .union())

a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)  # {1, 2, 3, 4, 5}

Intersection (& or .intersection())

print(a & b)  # {3}

Difference (- or .difference())

print(a - b)  # {1, 2}

Symmetric Difference (^ or .symmetric_difference())

print(a ^ b)  # {1, 2, 4, 5}

Set Methods Summary

MethodDescription
add()Add one item
update()Add multiple items
remove()Remove item (error if not found)
discard()Remove item (no error if not found)
pop()Remove a random item
clear()Empty the set
union()Combine two sets
intersection()Common elements
difference()Elements in one set but not the other
symmetric_difference()Elements in either set but not both

Best Practices

Use set() to remove duplicates from lists/tuples.
Use discard() instead of remove() to avoid runtime errors.
Leverage set math for clean filtering and comparison.
Convert data from files/inputs to sets for faster lookups.


Python Set Exercises

1. Remove Duplicates from a List

nums = [1, 2, 2, 3, 4, 4]
unique = list(set(nums))
print(unique)

2. Find Common Items Between Two Sets

a = {"a", "b", "c"}
b = {"b", "c", "d"}
print(a & b)

3. Combine Two Sets and Remove Duplicates

x = {1, 2}
y = {2, 3}
print(x | y)

4. Filter Items Not in Both Sets

x = {1, 2, 3}
y = {3, 4, 5}
print(x ^ y)

5. Safely Remove an Element

items = {"pen", "pencil", "eraser"}
items.discard("marker")  # no error
print(items)

Summary – Recap & Next Steps

Python sets offer unmatched performance for deduplication, fast lookups, and set-theoretic logic. With support for union, intersection, and difference operations, sets are a powerful tool for solving many programming challenges efficiently.

Key Takeaways:

  • Sets store unique, unordered elements.
  • Use .add(), .update(), .remove(), .discard() to manage items.
  • Perform set math using operators: |, &, -, ^.
  • Use sets to filter data and validate membership.

Real-World Relevance:
Sets are used in data science, validation checks, permission systems, and duplicate removal in large datasets.


FAQ Section – Python Sets


What is a set in Python?
A set is an unordered collection of unique items. Defined with {} or set().


Can sets contain duplicates?
No. Any repeated values are automatically removed.


What’s the difference between remove() and discard()?
remove() raises an error if the item doesn’t exist; discard() does not.


How to remove duplicates from a list using sets?
Convert it:

list(set([1, 2, 2, 3]))  # Output: [1, 2, 3]

Are sets mutable?
Yes. You can add/remove elements. For immutability, use frozenset.


Share Now :
Share

🔁 Python Sets

Or Copy Link

CONTENTS
Scroll to Top