Set Operations Examples In Python
A set is a collection which is unordered and unindexed.
Set operations examples in python. Consider these two sets. In python sets are written with curly brackets. If the optional iterable parameter is supplied updates the set with elements obtained from iteration. X x 3 modulus assignment.
X x 3 exponentiation assignment. Operators are used to perform operations on variables and values. X x 3 subtraction assignment. X x 3 floor division assignment.
My set1 add i adding elements to my set2 for i in range 3 8. Let s take a look at how these operators and methods work using set union as an example. Python divides the operators in the following groups. 8 0 6 symmetric difference.
X x 3 division assignment. My set3 my set3 intersection of my set1 and. Let us consider the following two sets for the following operations. A 1 2 3 4 5 b 4 5 6 7 8 set union set union in python.
A 0 2 4 6 8 b 1 2 3 4 5 output. Equivatent to assignment. 2 4 difference. We can do this with operators or methods.
For convenience in implementing sets of sets inner sets are automatically converted to immutable form for example set set dog is transformed to set immutableset dog. This article demonstrates different operations on python sets. My set2 add i print my set1 my set1 print my set2 my set2 print n union of my set1 and my set2 my set3 my set1 my set2 my set1 union my set2 print union of my set1 my set2. Python program to illustrate different set operations in this example we have defined two set variables and we have performed different set operations.
Most though not quite all set operations in python can be performed in two different ways. To create an empty set you have to use set not. Union intersection difference and symmetric difference. Given two sets x1 and x2 the union of x1 and x2 is a set consisting of all elements in either set.
0 1 2 3 4 5 6 8 intersection. Sets can be used to carry out mathematical set operations like union intersection difference and symmetric difference. X x 3 multiplication assignment. By operator or by method.
Example code python program to demonstrate working of set in python creating two sets my set1 set my set2 set adding elements to my set1 for i in range 1 6. Class sets set iterable constructs a new empty set object. Set objects also support mathematical operations like union intersection difference and symmetric difference. Curly braces or the set function can be used to create sets.