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

Python Sets: Creation and Operations

The document provides an overview of Python sets, which are unordered collections of unique elements that support operations like union, intersection, and difference. It includes details on creating sets, adding/removing elements, common methods, and the concept of frozensets for immutability. Additionally, it highlights practical examples, common pitfalls, and exercises for practice.

Uploaded by

dhronyadav1818
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 views16 pages

Python Sets: Creation and Operations

The document provides an overview of Python sets, which are unordered collections of unique elements that support operations like union, intersection, and difference. It includes details on creating sets, adding/removing elements, common methods, and the concept of frozensets for immutability. Additionally, it highlights practical examples, common pitfalls, and exercises for practice.

Uploaded by

dhronyadav1818
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

Python Programming — Unit 3: Sets

Department of Computer Science


MIET, Meerut

Fall 2025

Department of Computer Science MIET, Meerut Python Sets Fall 2025 1 / 16


Contents

1 Introduction to Sets
2 Creating Sets
3 Adding and Removing Elements
4 Set Operations
5 Membership and Comparison
6 Set Methods Table
7 Frozen Sets
8 Practical Examples
9 Pitfalls and Tips
10 Exercises
11 Summary

Department of Computer Science MIET, Meerut Python Sets Fall 2025 2 / 16


What is a Set? (Simple Explanation)

Definition
A set in Python is an unordered collection of unique elements. It is
used to store multiple items in a single variable without duplicates.

Sets are written using curly braces { } or by using the set()


constructor.
A set automatically removes duplicate values.
Set elements must be immutable (numbers, strings, tuples), but the
set itself is mutable.
Sets do not maintain order and cannot be indexed.

Department of Computer Science MIET, Meerut Python Sets Fall 2025 3 / 16


Creating Sets (Examples)
1 # using curly braces
2 numbers = {1, 2, 3, 4, 5}
3 print ( numbers )
4
5 # using set () constructor
6 letters = set (['a', 'b', 'c', 'a'
])
7 print ( letters )
8
9 # empty set
10 empty = set ()
11 print (type(empty))

Output
{1, 2, 3, 4, 5}
{'a', 'b', 'c'}
<class 'set'>
Department of Computer Science MIET, Meerut Python Sets Fall 2025 4 / 16
Adding and Removing Elements
1 A = {1, 2, 3}
2 [Link] (4) # add single
element
3 A. update ([5, 6]) # add
multiple elements
4 print (A)
5
6 A. remove (2) # remove
specific element
7 A. discard (10) # no error if
missing
8 popped = [Link] () # removes
random element
9 print (" After removals :", A)
10 print (" Popped :", popped )
11
12 [Link] () # remove all
elements
13 print (A)
Department of Computer Science MIET, Meerut Python Sets Fall 2025 5 / 16
Set Operations — Union, Intersection, Difference
1 A = {1, 2, 3, 4, 5}
2 B = {4, 5, 6, 7}
3
4 print (" Union :", A | B)
5 print (" Intersection :", A & B)
6 print (" Difference A-B:", A - B)
7 print (" Difference B-A:", B - A)
8 print (" Symmetric Difference :", A
^ B)

Output
Union: {1, 2, 3, 4, 5, 6, 7}
Intersection: {4, 5}
Difference A-B: {1, 2, 3}
Difference B-A: {6, 7}
Symmetric Difference: {1, 2, 3, 6, 7}

Department of Computer Science MIET, Meerut Python Sets Fall 2025 6 / 16


Membership and Comparison
1 A = {1, 2, 3, 4, 5}
2 print (3 in A) # True
3 print (10 in A) # False
4
5 B = {1, 2, 3}
6 print (B. issubset (A)) # True
7 print (A. issuperset (B)) # True
8
9 C = {10, 11}
10 print (A. isdisjoint (C)) # True

Output
True
False
True
True
True
Department of Computer Science MIET, Meerut Python Sets Fall 2025 7 / 16
Common Set Methods (Quick Reference Table)

Method Description Example / Res


add(x) Add single element [Link](5)
update(iter) Add multiple [Link]([1,2])
remove(x) Remove element (error if missing) [Link](3)
discard(x) Remove element (safe) [Link](10)
pop() Remove random element [Link]()
clear() Remove all elements [Link]()
union(t) Combine sets [Link](t) or s
intersection(t) Common elements s&t
difference(t) Subtract elements s-t
symmetric_difference(t) XOR elements s t̂
issubset(t) Check subset [Link](t)
issuperset(t) Check superset [Link](t)
isdisjoint(t) No common elements [Link](t)

Department of Computer Science MIET, Meerut Python Sets Fall 2025 8 / 16


Frozen Sets (Immutable Sets)

A frozenset is an immutable version of a set.


Once created, elements cannot be added or removed.
Useful when you need to use a set as a dictionary key.
1 A = frozenset ([1, 2, 3])
2 B = frozenset ([3, 4, 5])
3 print (A | B)
4 print (A & B)
5 # [Link] (6) # Error : frozenset
object has no attribute 'add '

Output
frozenset({1, 2, 3, 4, 5})
frozenset({3})

Department of Computer Science MIET, Meerut Python Sets Fall 2025 9 / 16


Example 1: Remove Duplicates from a List

1 data = [1, 2, 2, 3, 4, 4, 5]
2 unique = list(set(data))
3 print ( unique )

Output
[1, 2, 3, 4, 5]

Department of Computer Science MIET, Meerut Python Sets Fall 2025 10 / 16


Example 2: Find Common Students in Two Courses

1 course_A = {" Alice ", "Bob", "


Charlie "}
2 course_B = {"Bob", " David ", "Eve"
}
3
4 common = course_A & course_B
5 print (" Common students :", common )

Output
Common students: {'Bob'}

Department of Computer Science MIET, Meerut Python Sets Fall 2025 11 / 16


Example 3: Set Algebra Application
1 all_students = {"A","B","C","D","
E","F"}
2 cricket = {"A","B","C"}
3 football = {"B","D","E"}
4
5 # Students playing both
6 print ("Both:", cricket & football
)
7 # Students playing only cricket
8 print ("Only cricket :", cricket -
football )
9 # Students playing neither
10 print (" Neither :", all_students -
( cricket | football ))

Output
Both: {'B'}
Only cricket: {'A', 'C'}
Department of Computer Science MIET, Meerut Python Sets Fall 2025 12 / 16
Common Pitfalls and Tips

Sets are unordered — you can’t rely on the element order.


You can’t use lists or dictionaries inside sets (unhashable types).
Membership checks (in) are O(1) on average — very fast.
Use sets for deduplication and efficient membership operations.
For immutable sets, use frozenset().

Department of Computer Science MIET, Meerut Python Sets Fall 2025 13 / 16


Practice Exercises

1 Write a program to find the intersection and union of two sets.


2 Given two lists, find unique elements present in only one of them.
3 Check whether one set is a subset of another.
4 Create a program that counts unique words in a sentence using a set.

Department of Computer Science MIET, Meerut Python Sets Fall 2025 14 / 16


Summary — Python Sets

A set is an unordered collection of unique elements.


Supports mathematical operations: union, intersection, difference.
Fast membership testing and easy deduplication.
Use frozenset() when immutability is required.

Department of Computer Science MIET, Meerut Python Sets Fall 2025 15 / 16


Thank You!
Questions?

Department of Computer Science MIET, Meerut Python Sets Fall 2025 16 / 16

You might also like