Sets in Python
The set in Python is a built-in, mutable, and unordered collection data type that stores unique elements. This means duplicate items are automatically removed.
Sets are written with curly brackets ({}) or created using the built-in set() function.
Sets are used to store multiple items in a single variable.
Ex.1
set = {"apple", "banana", "orange"}
print(set)
Output
{'orange', 'banana', 'apple'}
Ex.2
no= {1, 2, 3, 4, 5}
print(no)
Output
{1, 2, 3, 4, 5}
Ex.3
Empty Set
Null Set=set()
Ex.4
s = {10, 50, 20}
print(s)
print(type(s))
Output
{10, 50, 20}
<class 'set'>
Duplicates Not Allowed
Duplicate values will be ignored.
Ex.
set = {"apple", "banana", "orange", "apple"}
print(set)
Output
{"apple", "banana", "orange"}
Note:
- True and 1 is considered the same value.
set = {"apple", "banana", "grapes", True, 1, 2}
print(set)
Output
{True, 2, 'banana', 'grapes', 'apple'}
- False and 0 is considered the same value and are treated as duplicates.
set = {"apple", "banana", "grapes", False, True, 0}
print(set)
Output
{False, True, 'apple', 'banana', 'grapes'}
Methods for Sets
add() Function
add() function is used to insert new elements into a set. It automatically ignores duplicates.
Ex.
s = {"a", "b", "c"}
s.add("d")
print(s)
Output
{'c', 'd', 'a', 'b'}
union() function
union() function combines two sets and returns a new set with all unique elements.
Ex.
a = {"x", "y"}
b = {"y", "z"}
u = a.union(b)
print(u)
Output
{'z', 'y', 'x'}
intersection() function
intersection() function returns a new set containing elements that are common to both sets.
Ex.
a = {1, 2, 3}
b = {2, 3, 4}
i = a.intersection(b)
print(i)
Output
{2, 3}
difference() function
difference() function returns a set containing elements that are in the first set but not in the second.
Ex.
a = {1, 2, 3}
b = {2, 3, 4}
i = a.difference(b)
print(i)
Output
{1}
clear() function
clear() function removes all elements from a set, leaving it empty.
Ex.
s = {1, 2, 3}
s.clear()
print(s)
Output
set()
pop() function
pop() function removes a random number.
Ex.
s = {1, 2, 3}
s.pop()
print(s)
Output
{2, 3}
Sets in Python
Reviewed by ADcomputercampus
on
March 16, 2026
Rating:

No comments: