Python Tutorial
Estimated reading: 4 minutes 31 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ” Python Sets

Or Copy Link

CONTENTS
Scroll to Top