Thursday, June 22, 2023

Python Set

 

Python set

 

Set is an unordered collections of items.Every element is unique (no duplicate values) must be immutable(which cannot be changed).

How  to create a set?

set of integers

my_set  =  {23,45,67}

print(my_set)

set of mixed  datatypes

my_set  = {10,"hai", (1, 2, 3),5.7,3+2j}

print(my_set)

 

set do not have duplicates

my_set  = {10,12,12,23,30,56,45,23}

print(my_set)

 

#set cannot have mutable items

here [3, 4] is  a mutable list

If you uncomment line #12,

this will cause an error.

TypeError: unhashable type: 'list'

my_set = {1, 2, [3, 4]}

 

#we can make set from a list

Output:

{1, 2, 3}

my_set = set([1,2,3,2])

print(my_set)

 

OUTPUT

set([67, 45, 23])

set([(3+2j),  10, 5.7, 'CSC', (1, 2,3)])

set([10, 12, 45, 23, 56, 30])

Trackback  (most  recent  call  last):

   File "C:/Python27/str", line 18, in  <module>

   my_set = {1, 2,[3, 4]}

TypeError : unhashable type:  'list'

 

#Creating an empty set is a bit tricky.

#initialize  a with {}

a  = {}

#check  data  type of a

Output: <class  'dict'>

print(type(a))

#initialize  a with set()

a  =set()

#check  data  type of a

Output: <class  'set'>

print(type(a))

 

How  to change a set in python?

#initialize  my_set

my_set  = {1,3}

print(my_set)

 

#if you uncomment line 9,

#you will get an error

#TypeError: 'set' object dose not support indexing

 

#my_set[0]

 

add an element

Output: {1, 2,3}

my_set.add(2)

print(my_set)

add multiple elements

Output: {1,2,3,4}

my_set.update([2,3,4])

print(my_set)

add list and set

Output: {1, 2, 3,4, 5, 6, 8}

my_set.update([4,5],  {1,6,8})

print(my_set)

When  you  run  the  program,  the output wil be:

{1, 3}

{1, 2, 3}

{1, 2, 3, 4}

{1, 2, 3, 4, 5, 6, 8}

 

How  to  remove  element from a set?

 Create a set with Natural numbers

Nset  =  {1,2,3,4,5,6,7,8,9}

print(Nset)

OUTPUT

set([1,  2, 3, 4, 5, 6, 7, 8, 9])

Remove  or discard an element

Nset.discard(3)

print(Nset)

OUTPUT

set([1,  2, 4, 5, 6, 7, 8, 9])

 

Another method to remove an element

    Nset.remove(9)

print(Nset)

OUTPUT

set([1,  2, 3, 4, 5, 6, 7, 8])

discard  an element not in Nset

Discard not raise any error if element not found in the set

Nset.discard (0)

print(Nset)

#remove an element not in Nset

#Remove raise an error if not found

#This the difference between discard() and remove()

Nset.remove(0)

OUTPUT

Trackback  (most  recent  call last):

 File "C:/Python27/str", line 17, in  <module>

   Nset.remove(0)

KeyError: 0

 > > >

create a vowels as a set elements

Vset  = set("AEIOU")

print(Vset)

OUTPUT

set(['A', 'I', 'E', 'U', 'O'])

#pop an element

print(Vset.pop())

OUTPUT

A

#pop another element

print(Vset.pop())

print(Vset)

OUTPUT

set(['E', 'U', 'O'])

Remove all the element  using clear()   Vset

Vset.clear()

print(Vset)

OUTPUT

set([])

 

Python set Operations

> > > SET_A  =  {3,4,5,6,7}

> > >SET_B   =  {3,6,8,9,1}

Set Union

  U

 

SA = {3,4,5,6,7}

SB = {3,6,8,9,1}

 

#Using / operator

print(SA|SB)

 

#Using union() method

print(SA.union(SB))

 

OUTPUT

set([1, 3, 4, 5, 6, 7, 8, 9])

set([1, 3, 4, 5, 6, 7, 8, 9])

Set Intersection

    U

       

SA = {3,4,5,6,7}

SB = {3,6,8,9,1}

Using & operator

print (SA & SB)

 

Using  intersection()  method

print(SA.intersection(SB))

 

OUTPUT

set([3, 6])

set([3, 6])

 

Set Difference

U

 

 SA = {3,4,5,6,7}

SB = {3,6,8,9,1}

Element  unique to SA

print("Element only in SA set ")

Using - operator

print(SA - SB)

 

Using difference () method

print(SA.difference(SB))

 

Element  unique to SB

 

print("Element only in SA set ")

print(SB - SA)

Print (SB.difference(SA))

 

OUTPUT

Element Only in SA set

set([4, 5, 6])

set([4, 5, 6])

Element  Only in SB set

set([8, 1, 9])

set([8, 1, 9])

 

Set Symmetric Difference

 

 Element not common in both sets

SA = {3,4,5,6,7}

SB = {3,6,8,9,1}

Using ^ operator

print(SA ^ SB)

 

Using symmetric_difference() method

print(SA. symmetric_difference(sb))

 

OUTPUT

set([1, 4, 5, 7, 8, 9])

set([1, 4, 5, 7, 8, 9])

 

set([1, 4, 5, 7, 8, 9])

Other Set Operations

Set membership

#initilize vowels in Vset

#Use  'in'  and  'not in ' operator to check the result

Vset =  set("AEIOU")

 

print('I'  in Vset)

print('S' in Vset)

 

print('K'  not in Vset)

print('A' not in Vset)

 

OUTPUT

True

False

True

False

 

lterating  Through  a Set

> > > for ch  in set ("Python")

...          print(ch)

...   

OUTPUT

 

P

Y

T

H

O

N

 

Built-in Function  With  Set

Function

Description

all()

Return true if all element of the set are true (or if the set is empty)

any()

Return true if any element of the set is true. if the set is empty, returen false

enumerate()

Return an enumberate object .it contains the index and value of all the items of set as a pair.

len()

Return the length (the number of items)in the set

max()

Return the largest item in the set

min()

Return the smallest item  in the set

sorted()

Return a new  sorted list from elements in the set(dose not sort the set it self)

sum()

Return the sum of all element in the set

 

Example for SET Built in function

 #set method

Nset = {1,2,3,4,5,6,7,8,9,}

print("\n actual set value =",Nset)

print("\n maximum of Nset ={}".format(max(Nset)))

print("\n minimum of Nset = {}".format(min(Nset)))

print("\n sum of Nset = {}".format(sum(Nset)))

print("\n any false value in Nset ={} is ".format(any(Nset)))

print("\n all true value in Nset = {}", .format(all(Nset)))

print("\n sorted value of Nset = {} ".format(sorted(Nset)))

print("\n length of Nset = {}".format(len(Nset)))

OUTPUT

Actual set value = set([1, 2, 3, 4, 5, 6, 7, 8, 9])

maximum of Nset = 9

minimum of Nset = 1

sum of Nset = 45

any false value in Nset = True

all true value in Nset = True

Sorted value of Nset=[1, 2, 3, 4, 5, 6, 7, 8, 9]

Length  of Nset = 9

 

Program to find the twoplayers Details Using SET

Team_A = set()                       

Team_B = set()

print("\n Enter playar name to add in Team A/n")

While True:

       str = input()

       Team_A.add(str)

        ch = input("Add[y/n]

       if ch in {'n', 'N'}:

          break

print("\n Enter playar name to add in Team B/n")

While True:

      str = input()

      Team_B.add(str)

      ch = input("Add[y/n]

      if ch in {'n', 'N'}:

        break

print ("/n Team A Players List:",Team_A)

print ("/n Team B Players List:",Team_B)

print ("/n Players only in Team A: ", Team_A:".difference(Team_B))

print ("/n Players only in Team B: ", Team_B:".difference(Team_A))

print ("/n Players in both Teams: ",Team_A.intersection (Team_B))

 

OUTPUT

Enter Playar Name to add in team A

Raj

Add.[y/n]?..y

Arun

Add.[y/n]?..y

Mani

Add.[y/n]?..y

Enter Playar Name to add in team A

Gopal

Add.[y/n]?..y

Arun

Add.[y/n]?..y

Bala

Add.[y/n]?..n

Team A Players list: {'Arun', 'Mani', 'Raj'}     

Team A Players list: {'Arun', 'Gopal', 'Bala'} 

Players Only in Team A: {'Mani', 'Raj'}

Players Only in Team B: {'Gopal', 'Bala'}

Players in Both Teams: {'Arun'}         

 


0 comments:

Post a Comment