Sets - Python Basics

Sets - Python Basics


In Python, a set is a built-in data structure used to store multiple items in a single variable. Unlike lists or tuples, sets are unordered, unindexed, and they do not allow duplicate values. Sets are widely used when you need to store unique data and perform operations like union, intersection, and difference.


Characteristics of Python Sets

  • Unordered – The items in a set have no defined order.
  • Unindexed – You cannot access items using indexes.
  • No Duplicates – Each item in a set must be unique.
  • Mutable – You can add or remove items after creation.
  • Heterogeneous – A set can contain different data types.

📌 Syntax of Python Sets


# Creating a Set
myset = {1, 2, 3, 4, 5}

# Creating an Empty Set (use set(), not {})
empty_set = set()

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


🔹 Uses of Sets in Python

  • ✔️ Removing duplicate items from a list.
  • ✔️ Performing mathematical set operations (union, intersection, difference).
  • ✔️ Fast membership testing using in keyword.
  • ✔️ Useful for data cleaning in applications like AI/ML, web scraping, and databases.

🎯 Access Set Items

You cannot access set items by index. Instead, you can loop through the set or check if an item exists.


myset = {"apple", "banana", "cherry"}

# Loop through set
for x in myset:
    print(x)

# Check if an item exists
print("banana" in myset)  # Output: True

➕ Add Set Items


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

# Add multiple items
fruits.update(["mango", "grape"])
print(fruits)

❌ Remove Set Items


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

fruits.remove("banana")  # Raises error if item not found
fruits.discard("mango")  # Does not raise error
fruits.pop()             # Removes a random item
fruits.clear()           # Empties the set

🔁 Loop Through Sets


numbers = {1, 2, 3, 4, 5}
for num in numbers:
    print(num)

🔗 Join Sets

We can join two sets using union() or update().


set1 = {"a", "b", "c"}
set2 = {1, 2, 3}

# Union (returns new set)
newset = set1.union(set2)
print(newset)

# Update (adds items into set1)
set1.update(set2)
print(set1)

⚡ Python Set Methods

MethodDescriptionExample
add()Adds an itemmyset.add("orange")
clear()Removes all itemsmyset.clear()
copy()Returns a copy of setnewset = myset.copy()
difference()Returns difference of setsset1.difference(set2)
difference_update()Removes common elementsset1.difference_update(set2)
discard()Removes item safelymyset.discard("banana")
intersection()Common itemsset1.intersection(set2)
isdisjoint()True if no common itemsset1.isdisjoint(set2)
issubset()True if set1 in set2set1.issubset(set2)
issuperset()True if set1 contains set2set1.issuperset(set2)
pop()Removes random itemmyset.pop()
remove()Removes specific itemmyset.remove("apple")
symmetric_difference()Unique in both setsset1.symmetric_difference(set2)
union()Returns unionset1.union(set2)
update()Updates set with othersset1.update(set2)

📝 Python Set Exercises


# Exercise 1: Remove duplicates from list
nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = set(nums)
print(unique_nums)

# Exercise 2: Find common elements
setA = {"apple", "banana", "cherry"}
setB = {"banana", "kiwi", "cherry"}
print(setA.intersection(setB))

# Exercise 3: Check subset
setX = {1, 2}
setY = {1, 2, 3, 4}
print(setX.issubset(setY))

# Exercise 4: Symmetric difference
set1 = {10, 20, 30}
set2 = {20, 40, 50}
print(set1.symmetric_difference(set2))

❓ FAQs on Python Sets

Q1. Can sets contain duplicate values?
No, sets automatically remove duplicate values.

Q2. Can sets store different data types?
Yes, sets can contain mixed types (int, str, float, etc.).

Q3. What is the difference between remove() and discard()?
remove() raises an error if the item does not exist, while discard() does not.

Q4. When should I use sets instead of lists?
Use sets when you need unique elements and fast lookups.


✅Conclusion

Python sets are powerful when you need to work with unique elements and perform mathematical set operations. They are fast, memory-efficient, and widely used in real-world applications. Mastering set operations will make your Python coding more efficient and clean.


🔗 Related Python Tutorials


👉 Continue Learning: Explore more beginner-friendly topics and practice materials in our Programming Resource Hub.

Post a Comment

0 Comments