Python Sets

🐍 Python Sets — Complete Tutorial

A set in Python is a collection of unordered, mutable, and unique items.


✔ Key Characteristics of Sets

Feature Description
Unordered Items do not have a fixed position (no indexing)
Mutable You can add or remove items
Unique items No duplicate values are allowed
Iterable You can loop through sets

🔹 Creating a Set

my_set = {1, 2, 3, 4}
print(my_set)

If you create an empty set, you must use set(), because {} creates a dictionary.

empty_set = set()
print(type(empty_set))

🔹 Set Removes Duplicate Values

numbers = {1, 2, 2, 3, 4, 4}
print(numbers) # Output: {1, 2, 3, 4}

🔹 Accessing Set Items

Since sets are unordered, you cannot use indexing, but you can loop:

for item in numbers:
print(item)

🔹 Adding Items to a Set

add() — Add a single element

numbers.add(5)
print(numbers)

update() — Add multiple elements

numbers.update([6, 7, 8])
print(numbers)

🔹 Removing Items from a Set

Method Behavior
remove() Removes an element; error if not found
discard() Removes element; no error if not found
pop() Removes a random element
clear() Removes all elements

Examples:

numbers.remove(3)
numbers.discard(10) # No error
print(numbers)
random_item = numbers.pop()
print(“Popped:”, random_item)

numbers.clear()
print(numbers)


🔹 Set Operations (Important)

Python sets support mathematical set operations.

1️⃣ Union (| or union())

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

2️⃣ Intersection (& or intersection())

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

3️⃣ Difference (- or difference())

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

4️⃣ Symmetric Difference (^ or symmetric_difference())

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

🔹 Check Membership

print(2 in A) # True
print(10 in A) # False

🔹 Copying a Set

C = A.copy()
print(C)

🔹 Frozen Set (Immutable Set)

A frozenset is unchangeable.

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

🏆 Summary Table

Operation Method
Add element add()
Add multiple values update()
Remove with error remove()
Remove without error discard()
Remove random item pop()
Union union() or `
Intersection intersection() or &
Difference difference() or -
Symmetric Difference symmetric_difference() or ^

🧠 Practice Exercises

Try these now:

  1. Create a set with values: 10, 20, 30, 40, 50.
    Add 60 and remove 20.

  2. Given:

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

Find:

  • Union

  • Intersection

  • Difference

  • Symmetric Difference

  1. Convert this list to a set and remove duplicates:

nums = [1, 2, 2, 3, 4, 4, 5]

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

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