0% found this document useful (0 votes)
3 views14 pages

4 Set Data Structure

The document provides an overview of Python's set data structure, highlighting its characteristics such as no duplicate elements, unordered collection, and efficient operations due to hashing. It explains how to create sets, add or remove elements, and perform various set operations like union, intersection, and difference. Additionally, it lists methods available for set manipulation and demonstrates their usage with examples.

Uploaded by

ShaaN
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)
3 views14 pages

4 Set Data Structure

The document provides an overview of Python's set data structure, highlighting its characteristics such as no duplicate elements, unordered collection, and efficient operations due to hashing. It explains how to create sets, add or remove elements, and perform various set operations like union, intersection, and difference. Additionally, it lists methods available for set manipulation and demonstrates their usage with examples.

Uploaded by

ShaaN
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 set data structure

• No duplicate elements. If try to insert the same item again, it overwrites


previous one.
• An unordered collection. When we access all items, they are accessed
without any specific order and we cannot access items using indexes as we
do in lists.
• Internally use hashing that makes set efficient for search, insert and delete
operations.
• Mutable, meaning we can add or remove elements after their creation, the
individual elements within the set cannot be changed directly.

Creating a Set
numbers = {2, 4, 6, 6, 2, 8}
s = {10, 50, 20} print(numbers)
s = {1,2,3}
print(s)
s = set([1,2,3]) {8, 2, 4, 6}
print(type(s)) Output
{10, 50, 20}
<class 'set'>
# create a set of integer type
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)

# create a set of string type


vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)

# create a set of mixed data types


mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)

Student ID: {112, 114, 115, 116, 118}


Vowel Letters: {'u', 'a', 'e', 'i', 'o'}
Set of mixed data types: {'Hello', 'Bye', 101, -2}
Adding and Removing elements
We can add and remove elements form the set with the help of the below
functions -
• add(): Adds a given element to a set.
• clear(): Removes all elements from the set.
• discard(): Removes the element from the set. No error if missing.
• pop(): Returns and removes a random element from the set.
• remove(): Removes the element from the set. Error if missing.
n = int(input("Enter number of elements: "))
s = set()
i=0
while i < n:
x = int(input("Enter element: "))
[Link](x)
i += 1
print("Set elements:", s)

Enter number of elements: 3


Enter element: 1
Enter element: 2
Enter element: 3
Set elements: {1, 2, 3}
# set of letters
s = {'e', 'g', 'k', 's'}
# adding 's'
[Link]('f')
print('Set after updating:', s)
# Discarding element from the set
[Link]('g')
print('\nSet after updating:', s)
# Removing element from the set
[Link]('e')
print('\nSet after updating:', s)
# Popping elements from the set
print('\nPopped element', [Link]())
print('Set after updating:', s)
[Link]()
print('\nSet after updating:', s)
Set after updating: {'k', 'g', 'e', 's', 'f'}
Set after updating: {'k', 'e', 's', 'f'}
Set after updating: {'k', 's', 'f'}
Popped element k
Set after updating: {'s', 'f'}
Set after updating: set()
• A set can have any number of items and may be of different types (integer, float, tuple,
string, etc.).
• But a set cannot have mutable elements like lists, sets or dictionaries as its elements.

Set Operations
• Union |
• Intersection &
• Difference -
Find Union of Two Sets Find Intersection of Two Sets
s1 = set() a = set()
s2 = set() b = set()

n = int(input("Enter number of elements: "))


n1 = int(input("Enter size of first set: ")) for i in range(n):
for i in range(n1): [Link](int(input("Enter element for set A: ")))
[Link](int(input("Enter element: ")))
i=0
while i < n:
n2 = int(input("Enter size of second set: ")) [Link](int(input("Enter element for set B: ")))
i=0 i += 1
while i < n2:
[Link](int(input("Enter element: "))) print("Intersection:", a & b)
i += 1

print("Union:", s1 | s2)
Find Difference of Two Sets
s1 = set()
s2 = set()

n = int(input("Enter number of elements: "))


for i in range(n):
[Link](int(input("Enter element for set 1: ")))

i=0
while i < n:
[Link](int(input("Enter element for set 2: ")))
i += 1

print("Difference (s1 - s2):", s1 - s2)


Accessing Set Elements
• Using loop only
• No indexing
Method Shortcut Description
add() Adds an element to the set
clear() Removes all the elements from the set

copy() Returns a copy of the set


difference() - Returns a set containing the difference
between two or more sets

difference_update() -= Removes the items in this set that are also


included in another, specified set

discard() Remove the specified item


Method Shortcut Description
intersection() & Returns a set, that is the intersection of two other
sets
intersection_update() &= Removes the items in this set that are not present in
other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() <= Returns True if all items of this set is present in
another set
< Returns True if all items of this set is present in
another, larger set
issuperset() >= Returns True if all items of another set is present in
this set
> Returns True if all items of another, smaller set is
present in this set
Method Shortcut Description
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() ^ Returns a set with the symmetric
differences of two sets
symmetric_difference_update() ^= Inserts the symmetric differences from this
set and another
union() | Return a set containing the union of sets
update() |= Update the set with the union of this set
and others
fruits = {"apple", "banana", "cherry"}
x = [Link]()
print(x) {'cherry', 'banana', 'apple'}

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


y = {"google", "microsoft", "apple"}
x.difference_update(y)
{'cherry', 'banana'}
print(x)

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


y = {"google", "microsoft", "facebook"}
z = [Link](y) True
print(z)

x = {"a", "b", "c"}


y = {"f", "e", "d", "c", "b", "a"} True
z = [Link](y)
print(z)
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = [Link](y) True
print(z)

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


y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y) {'google', 'cherry', 'microsoft', 'banana'}
print(z)

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


y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x) {'google', 'microsoft', 'cherry', 'banana'}

You might also like