Welcome

sampleqa.in tutorials, python tutorial

Python tutorial


Python Set Operations

methoddescription

      The following Arithmetic and bitwise operators can be applied on Sets.

  • & (Intersection)
  • | (Union)
  • - (difference)
  • ^ (symmetric difference)

Create a Set Objects

		>>> set1=set('abcd')
		>>> set2=set('abcdef')
	
		>>> set1
		{'b', 'd', 'a', 'c'}
		>>> set2
		{'e', 'f', 'b', 'd', 'a', 'c'}
		>>> 	
	

Set Union Operation using |

   The set that contains all elements of two or more sets

	>>> set1 | set2
	{'e', 'f', 'b', 'd', 'a', 'c'}
	>>> 	
	

Set Intersection Operation using &

   The set that contains all elements common to all sets

	>>> set1 & set2
	{'b', 'd', 'a', 'c'}
	>>> 	
	

Set Difference Operation using -

    The set contains all elements from set1 that doesnot exists in set2

	>>> set1 - set2
	set()
	>>>  
	>>>set2 -  set1
	{'e', 'f'}
	

Set Symmetric Difference Operation using ^

    The set that contains all elements belonging to either of given two sets but not to the both;

	>>> set1 ^ set2
	{'e', 'f'}
	>>> 
	>>>set2  ^ set1
	{'e', 'f'}
	

ADS