0% found this document useful (0 votes)
15 views3 pages

Understanding Sets in Python

Uploaded by

keerthana311004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views3 pages

Understanding Sets in Python

Uploaded by

keerthana311004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Day-10

✅ What is a Set in Python?


 A Set is an unordered collection of unique elements in Python.
 Duplicates are not allowed.
 Implemented using hashing (similar to HashSet in Java).
 Mutable (we can add or remove elements).
 Does not maintain insertion order (output may differ in order).
 Unindexed (we cannot access elements using an index).

✅ Key Points of Set

 Declared using curly braces {} or set() constructor.


 Elements must be hashable (immutable like int, str, tuple).
 Duplicates automatically removed.

✅ Types of Sets in Python


1. set – Normal set (mutable, unordered).
2. frozenset – Immutable set (cannot add/remove elements).

✅ Common Operations
Operation Method/Operator
Add element add()
Remove element remove(), discard()
Union union() or `
Intersection intersection() or &
Difference difference() or -
Subset Check issubset()
Superset Check issuperset()

✅ Examples with Output


1. Creating a Set
# Normal set
my_set = {1, 2, 3, 3, 2, 1}
print("Set:", my_set)

# Using set() constructor


another_set = set([4, 5, 6, 6])
print("Another Set:", another_set)

# Empty set
empty_set = set()
print("Empty Set:", empty_set)

Output:

Set: {1, 2, 3}
Another Set: {4, 5, 6}
Empty Set: set()

2. Adding & Removing Elements


s = {10, 20, 30}
[Link](40) # Add element
print("After add:", s)

[Link](20) # Remove element


print("After remove:", s)

[Link](100) # No error if element not present


print("After discard:", s)

Output:

After add: {40, 10, 20, 30}


After remove: {40, 10, 30}
After discard: {40, 10, 30}

3. Set Operations
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print("Union:", A | B)
print("Intersection:", A & B)
print("Difference (A-B):", A - B)
print("Symmetric Difference:", A ^ B)

Output:

Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference (A-B): {1, 2}
Symmetric Difference: {1, 2, 5, 6}
4. Checking Membership & Subsets
A = {1, 2, 3}
B = {1, 2}

print(2 in A) # Check if element exists


print([Link](A)) # Check subset
print([Link](B)) # Check superset

Output:

True
True
True

5. Frozenset (Immutable Set)


fs = frozenset([1, 2, 3])
print("Frozenset:", fs)
# [Link](4) # ERROR: frozenset is immutable

Output:

Frozenset: frozenset({1, 2, 3})

You might also like