Beginner Level, Learn Python

Day 14 – Master Sets in Python – Basics & Operations | 60 Days Python Crash Course | ElectroLab

Sets In python.

Sets in Python – Basics & Operations

Introduction

In Python, a Set is a powerful built-in data type that allows you to store unordered, unique elements. Sets are especially useful when you need to ensure data uniqueness, eliminate duplicates, or perform efficient mathematical set operations like union, intersection, and difference. In today’s lesson, we will explore everything you need to know about sets in Python to make your coding journey smoother and smarter.

Sets in Python are similar to lists and tuples, but with a key difference: no duplicate values and no indexing. This makes them extremely efficient for operations involving large datasets where repetition and order don’t matter.


What You’ll Learn Today:

  • What is a Set in Python
  • Creating sets
  • Adding and removing items
  • Set operations: union, intersection, difference
  • Iterating through sets
  • Built-in set methods
  • Common mistakes and real-world applications

Sets in Python: The Basics

Sets in Python – Basics & Operations

What is a Set?

A sets in Python is an unordered collection of items that are unique and immutable (the elements themselves must be immutable). However, the set itself is mutable, meaning you can add or remove elements after creation.

# Creating a basic set
fruits = {"apple", "banana", "mango"}
print(fruits)

Key Features of Sets:

  • Unordered: No guaranteed order
  • No duplicates: Each item is unique
  • Mutable: You can add or remove items

Creating Sets in Python

# Using curly braces
colors = {"red", "green", "blue"}

# Using set() constructor
numbers = set([1, 2, 3, 4])

# Creating an empty set
empty_set = set()  # NOT {}

Note: {} creates an empty dictionary, not a set.


Adding & Removing Elements

my_set = {1, 2, 3}

# Add elements
my_set.add(4)

# Remove element safely
my_set.discard(2)  # Won't raise an error if 2 doesn't exist

# Remove element with error if not found
my_set.remove(3)

Set Operations in Python

Sets are ideal for mathematical operations like:

1. Union

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

2. Intersection

print(A.intersection(B))  # or A & B

3. Difference

print(A.difference(B))  # or A - B

4. Symmetric Difference

print(A.symmetric_difference(B))  # or A ^ B

Iterating Through a Set

my_set = {"apple", "banana", "cherry"}
for item in my_set:
    print(item)

Reminder: Sets are unordered. You can’t rely on item positions.


Built-in Set Methods

  • add()
  • remove()
  • discard()
  • pop()
  • clear()
  • union()
  • intersection()
  • difference()
  • issubset(), issuperset()
  • copy()

Common Mistakes to Avoid

  1. Using {} to create an empty set a = {} # This is a dictionary, not a set! a = set() # Correct way
  2. Expecting Order my_set = {1, 2, 3} print(my_set[0]) # Error! Sets do not support indexing.
  3. Adding mutable types like lists my_set = set() my_set.add([1, 2]) # Error! Lists are unhashable

Real-Life Use Cases of Sets in Python

  • Data de-duplication: emails = ["a@gmail.com", "b@gmail.com", "a@gmail.com"] unique_emails = set(emails) print(unique_emails)
  • Tags or categories in blog posts
  • Fast membership tests: if "admin" in user_roles:
  • Performing intersection of user preferences or datasets

Quizzes

  1. What will be the output?
s = {1, 2, 3, 4}
s.add(4)
print(s)

A) {1, 2, 3, 4, 4}
B) {1, 2, 3, 4}
C) Error

Answer: B

  1. Which of these will raise an error?
s = set([1, 2, 3])
s.remove(5)

A) Yes
B) No

Answer: A

  1. Sets support indexing: True or False?

Answer: False


FAQs

Q1. Can sets contain duplicate items?
No, sets automatically remove duplicates.

Q2. How do I create an empty set?
Use set(), not {}.

Q3. Are sets faster than lists for membership tests?
Yes, sets are optimized for such operations.


Summary

Recap:

  • Sets store unique, unordered items.
  • Cannot access items via index.
  • Very useful for mathematical operations.
  • Several built-in methods help modify and inspect sets.

External Resources


Internal Links – Learn More with ElectroLab.in


What’s Next?

In the next lesson, we will dive into Dictionaries in Python, where you learn how to work with key-value pairs and perform efficient data mapping.

Stay tuned and keep practicing at ElectroLab.in!

author-avatar

About Mr Jyotiprasad

𝘉𝘶𝘪𝘭𝘥𝘪𝘯𝘨 𝘣𝘰𝘵𝘴, 𝘢𝘶𝘵𝘰𝘮𝘢𝘵𝘪𝘯𝘨 𝘭𝘪𝘧𝘦 🤖📡 | 𝘗𝘰𝘸𝘦𝘳𝘦𝘥 𝘣𝘺 𝘤𝘢𝘧𝘧𝘦𝘪𝘯𝘦 & 𝘤𝘶𝘳𝘪𝘰𝘴𝘪𝘵𝘺 ☕

Leave a Reply

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