In [1]:
my_set = set([1,2,3,4,5])
In [2]:
print(my_set)
{1, 2, 3, 4, 5}
In [3]:
#another way of creating set
my_set = {1,2,3,4,5}
In [4]:
print(my_set)
{1, 2, 3, 4, 5}
In [5]:
#for empty set
my_set = {}
print(type(my_set))
#by this way it will create an empty dictionary
<class 'dict'>
In [6]:
#To create empty set
my_set = set()
print(type(my_set))
<class 'set'>
In [7]:
#set removes duplicate values
my_set = {1,2,3,4,5,1,2,3}
print(my_set)
{1, 2, 3, 4, 5}
In [8]:
#adding 1 value to set
my_set.add(6)
print(my_set)
{1, 2, 3, 4, 5, 6}
In [9]:
#adding multiple values to set
my_set.update([7,8,9])
print(my_set)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
In [10]:
s2={9,10,11}
#updating set with another set
my_set.update(s2)
print(my_set)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
In [11]:
#Removing values from set
my_set.remove(5)
print(my_set)
{1, 2, 3, 4, 6, 7, 8, 9, 10, 11}
In [12]:
my_set.discard(6)
print(my_set)
{1, 2, 3, 4, 7, 8, 9, 10, 11}
In [13]:
#the difference between remove and discard method in sets is that discard won't throw an KeyError if the value doesn't exist but remove will
In [16]:
s1={1,2,3}
s2={2,3,4}
s3={3,4,5}
In [17]:
#values which are in s1 and s2
s4 = s1.intersection(s2)
print(s4)
{2, 3}
In [18]:
#values which are in s1,s2 and s3
s4 = s1.intersection(s2,s3)
print(s4)
{3}
In [19]:
#valus which are in s1 but not in s2
s5=s1.difference(s2)
print(s5)
{1}
In [20]:
s5=s2.difference(s1,s3)
print(s5)
#no values in s2 which are not in s1 and s3
set()
In [21]:
s5=s3.difference(s1,s2)
print(s5)
{5}
In [22]:
#this will return values which are unique in both set
s6=s1.symmetric_difference(s2)
print(s6)
{1, 4}
In [23]:
employees = ['Corey','Jim','Steven','April','Judy','Jenn','John',"Jane"]
gym_members = ['April','John',"Corey"]
developers = ['Judy', 'Corey', 'Steven', 'Jane', 'April']
In [26]:
#Developers having gym membership
result = set(developers).intersection(gym_members)
print(result)
{'Corey', 'April'}
In [27]:
#employees that are not developers or gym members
result = set(employees).difference(gym_members,developers)
print(result)
{'Jim', 'Jenn'}