Sunday, May 17, 2026

Python Material - Part - 8 - Set

 __author__ = "Narendra Boyina"

# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
#-----------------------------------------------------------------------------
"""
Topics to be covered in today's class:

--> Introduction to Sets
--> Adding Elements to a Set
--> Set Operations
--> Advanced Set Methods
--> Frozensets

--> common methods: ('clear', 'copy', 'difference', 'discard',
'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset',
'pop', 'remove', 'symmetric_difference', , 'union', 'update')
"""

""" # Introduction to Sets
--> set is a heterogeneous mutable unordered collection of unique elements
--> Delimited by { elements }, comma separated
--> sets are mainly useful for removing duplicates from sequences, membership tests,
and performing mathematical set operations """

""" # Creating different Sets
--> Creating an Empty set
empty {} makes a dictionary, So for empty set, use the set()constructor.
--> Creating a Set with data"""

# --> Creating an Empty set
# a = {} #empty dictionary
# print(type(a)) # <type 'dict'>
# empty_set = set()
# print("Empty set:", empty_set, type(empty_set)) # # <type 'set'>

# Creating a Set with data
fruits = {"apple", "banana", "Mango"}
# print("Set of fruits:", fruits) # Output: {'banana', 'Mango', 'apple'}

"""
# set() constructor accepts:
a. iterable series of values s = set([2,4.5,"apple", "banana", ["Mango", 65536], (2,"banana"]))
b. duplicates are discorded
t = [2, 4, 16, 4096, 4, 65536, 16]
print(set(t)) # set([16, 4096, 2, 4, 65536])
c. often used specifically to remove duplicates - not order preserving."""

# l = [2, 4, 16, 40.96, 4, 65536, 16,"Swetha"]
fruits_list = ["apple","Grapes", "banana", "Mango", "Grapes","Pineapple", "banana"]
# fruits_set = set(fruits_list) # set() constructor often used specifically to remove duplicates
# print(fruits_set, len(fruits_set))

""" # Adding Elements to a Set
Syntax: object.add(element)
"""
fruits_set = {'apple', 'Grapes', 'banana', 'Mango', 'Pineapple'} # taken fresh fruits set
# fruits_set.add("Kiwi") # we can add strings
# print(fruits_set) # {'banana', 'Pineapple', 'Mango', 'Kiwi', 'Grapes', 'apple'
# fruits_set.add("Mango") # we can add strings
# print(fruits_set) # This has no effect if the element is already present.
# fruits_set.add(472) # we can add integers
# print(fruits_set)
# fruits_set.add(44.5) # we can add float
# print(fruits_set)

"""If we want to add multiple elements at a time, we can use update(iterable) method, by passing any iterable series
Syntax: object.update(iterable)"""
fruits_set = {'coconut', 'guava'}

summer_fruits = ["jackfruit", "mango", "watermelon"] # list elements we can add to the set (Reason:- set is mutable)
# fruits_set.update(summer_fruits)
# print(fruits_set)

winter_fruits = ("Custard apples", "Grapes", "Kiwi", "Pears", "Pomegranate") # tuple elements we can add to th set (Reason:- set is mutable)
fruits_set.update(winter_fruits)
# print(fruits_set) # o/p :

Rainy_season_fruits = {"Litchi", "Jamun", "Cherry"} # set elements we can add to th set (Reason:- set is mutable)
fruits_set.update(Rainy_season_fruits) # tuple elements we can add to th set (Reason:- set is mutable)
# print(fruits_set) # o/p :

"""
2 methods are provided to removing elements from set
a. obj.remove(element) requires that item is present, otherwise raises KeyError
set.remove(element) # if element present, element will be removed,
set.remove(element) # if element not present, gives KeyError: element
b. set.discard(element) always succeeds (if element present, element will be removed,
if element not present it will do nothing) """
# Removing Elements from a Set
fruits_set = {'guava', 'Pomegranate', 'Cherry', 'coconut', 'Grapes', 'Pears', 'Litchi', 'Kiwi', 'Jamun', 'Custard apples'}
# print(fruits_set)
# fruits_set.remove("banana") # KeyError: banana (Errors if element is not present)
# print("After removing 'banana':", fruits_set)

fruits_set.remove("Cherry")
# print("After removing 'Cherry':", fruits_set)

# Discarding Elements (if element found, element will be removed)
fruits_set.discard("apple")
# print("After discarding 'apple':", fruits_set)

# Discarding Elements (if element found, element will be removed( No Errors if item is not present also))
fruits_set.discard("Pomegranate") # Always succeeds
# print("After discarding 'Pomegranate':", fruits_set)

""" Popping an Element (removes and returns an arbitrary element) """
# print("before popping an element:", fruits_set)
# popped_element = fruits_set.pop()
# print("Popped element:", popped_element) # Output: 'cherry' (or any other element)/ everytime it will remove different
# print("After popping an element:", fruits_set) # Output: {'apple', 'orange'}

"""Clearing a Set (removes all elements)"""
# fruits_set.clear()
# print("After clearing the set:", fruits_set) # Output: set()

""" # copying in 2 ways
==> set_obj.copy() method
==> set(s) constructor """

fruits_set_1 = {'apple', 'Grapes', 'banana', 'Mango', 'Pineapple'} # taken fresh fruits set
# fruits_set_2 = fruits_set_1.copy() # deep copy
# print(fruits_set_2)
# print(id(fruits_set_1), id(fruits_set_2)) # deep copy (creates the separate memory location)

# fruits_set_3 = set(fruits_set_1) # deep copy
# print(fruits_set_3)
# print(id(fruits_set_1), id(fruits_set_3)) # deep copy (creates the separate memory location)

fruits_set_4 = fruits_set_1 # shallow copy
# print(fruits_set_4)
# print(id(fruits_set_1), id(fruits_set_4)) # shallow copy (uses same memory location)

"""Set Operations : Python's set class represents the mathematical notion of a set."""
# Union of Sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# union_set = set1.union(set2)
# print("Union of set1 and set2:", union_set) # Output: {1, 2, 3, 4, 5}

# # Intersection of Sets
intersection_set = set1.intersection(set2)
# print("Intersection of set1 and set2:", intersection_set) # Output: {3}
#
# # Difference of Sets
difference_set = set1.difference(set2) # Equivalent to set1 - set2
# print("Difference of set1 and set2:", difference_set) # Output: {1, 2}
#
# # Symmetric Difference of Sets
symmetric_difference_set = set1.symmetric_difference(set2)
# print("Symmetric difference of set1 and set2:", symmetric_difference_set)
# # Output: {1, 2, 4, 5}
#
# # Checking Disjoint Sets --> 'Return True if two sets have a null intersection
# dd_set = {6, 7}
# print("Are set1 and dd_set disjoint?", set1.isdisjoint(dd_set))
# # Output: True


"""
Frozenset: Frozenset is an Immutable version of python set (like List & tuple)
While elements of a set can be modified at any time,elements of the frozenset remain the same after creation.
i.e there is no methods like add, update, remove
Syntax: frozenset(iterable) Ex:frozenset(string/list/tuple/set)
fronzenset() is a an inbuilt method.

"""

input_iterable = ["a", "narendra", "i", "o", "u"]
# fset = frozenset(input_iterable)
# print(fset)
# fset.add("suresh") # AttributeError: 'frozenset' object has no attribute 'add'
# fset.remove("narendra") # AttributeError: 'frozenset' object has no attribute 'remove'

""" ---------------------------------------------------------------------------
Practice Programs
-----------------------------------------------------------------------------"""

# # Return True if A is a subset of B &
# # False if A is not a subset of B
A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
C = {1, 2, 4, 5}
#
# Returns True
# print(A.issubset(B))
# #
# # # # # Returns False
# #
# print(B.issubset(A)) # B is not subset of A
# # #
# # # # # Returns False
# print(A.issubset(C))


A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
C = {1, 2, 4, 5}

# print(A.issuperset(B))
# print(B.issuperset(A))
# print(A.issuperset(C))



# #Set difference()
A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}

# # # Equivalent to A-B
# print(A.difference(B)) # {'b', 'a', 'd'}

# Equivalent to B-A
# print(B.difference(A)) # {'g', 'f'}


## intersection()
A = {2, 3, 5, 4}
B = {2, 5, 100}
C = {2, 3, 8, 9, 10}
#
#
# print(B.intersection(A)) # {2, 5}
# print(B.intersection(C)) # {2}
# print(A.intersection(C)) # {2, 3}
# print(C.intersection(A, B)) # {2}
#
# print(A.union(B)) # {2, 3, 4, 5, 100}
# print(B.union(C))

input_iterable = ["a", "e", "i", "o", "u"]
# print(type(input_iterable)) # python inbuilt methods ---> it will give the data type/ data structure
# print(id(input_iterable)) # python inbuilt methods ---> it will give the memory location
# print(len(input_iterable)) # python inbuilt methods ---> it will give the no of characters/elements / items/
# print(min(input_iterable)) # python inbuilt methods ---> Based on ASCII values, it will give the Min element of the iterable
# print(max(input_iterable)) # python inbuilt methods ---> Based on ASCII values, it will give the Max element of the iterable

Author: Boyina Narendra

Supporting Author: M. Meera Sindhu

Request: If you find this information useful, please provide your valuable comments

No comments:

Post a Comment