A set is a built-in data type in Python that represents an unordered collection of unique elements.
Key Features:
Unordered: The elements have no fixed position.
Unique: Duplicate values are automatically removed.
Mutable: You can add or remove elements.
Iterable: You can loop through a set.
#declare an empty set
set1=set()
set1.add('a1')
set1.add('b1')
set1.add('c1')
set1.add('d1')
set1.add('e1')
set1.add('f1')
print(set1)
# declare a set with values
set2={1,2,3,4,5,'q','r','t'}
print(set2)
# output
# {'b1', '3', 'e1', 'f1', 'a1'}
set1.update('3') #adds values to set
set1.remove('c1') #removes value from set
set1.discard('d1') #removes value from set
print(set1)
# output
# {'e1', 'd1', 'b1', 'a1', '3', 'f1'}
# initialize a set with duplicate values and print
set3={'john','george','john'}
print(set3)
# output
# {'john', 'george'}
# try to remove an element from the set1 which is not in that particular set
#set1.remove('x')
# output
# Traceback (most recent call last):
# File "c:\Users\Admin\OneDrive\Documents\Python Scripts\set_exercise.py", line 32, in <module>
# set1.remove('x')
# KeyError: 'x'
# try to discard an element from the set1 which is not in that particular set
set1.discard('x')
# it will not throw any error
# Now add 1,2 and 't' to the set1 at once
set1.update([1,2,'t'])
# then print the three sets
print ("Set1=",set1)
print ("Set2=",set2)
print ("Set3=",set3)
# output
# Set1= {1, 2, 'e1', 'a1', 'b1', '3', 'f1', 't'}
# Set2= {1, 2, 3, 4, 5, 't', 'q', 'r'}
# Set3= {'george', 'john'}
union_set1=set1.union(set2).union(set3)
print(union_set1)
# {1, 2, 3, 4, 5, '3', 'john', 'q', 't', 'george', 'r', 'f1', 'b1', 'e1', 'a1'}
intersection_set1=set1.intersection(set2)
print(intersection_set1)
# output:
# {1, 2, 't'}
# now if we print set1, we'll see that the set1 has not been changed.If we want to update the set1 by intersecting set2 then we can do it as below.
print("Set1 before intersection_update=",set1)
set1.intersection_update(set2)
print("Set1 after intersection_update=",set1)
# updating a set with multiple data types-list,tuple and set -> [1,2] is a list, (3,4) is a tuple, {4,5,6,'a'} is a set
new_set={0}
new_set.update([1,2],(3,4),{4,5,6,'a'})
print(new_set)
print(type(new_set))
#output:
#{0, 1, 2, 3, 4, 5, 6, 'a'}
#<class 'set'>
# Define a set with fruits
fruits = {'apple', 'banana', 'cherry'}
# Iterate through the set
for fruit in fruits:
print(fruit)
# Output:
# cherry
# banana
# apple