In this tutorial we are going to discuss about the sets.
Introduction:
Python provides a built in function called sets.
sets consists of following properties :-
- sets are unordered.
- set elements are unique.
- set does not allow duplicate values.
- sets are immutable.
Example:
Input:
set1={"app" ,"exp ","fox ","dog"}
print(set1)
Output:
{"app", "exp", "fox", "dog"}
Get the length of set:
To get the length of set we are using the function len().
Example:
Input:
set1={"apple", "banana", "mango"}
print. len(set1)
Output:
3
Add items:
Once the set is created you cannot change the set but you can add the items into it.
Example:
Input:
set1={"apple", "banana", "mango"}
print. add("orange)
Output:
{"apple", "banana", "mango", "orange"}
Remove items:
To remove the items in a set we use a function remove().
Example:
Input:
set1={"apple", "banana", "mango", "orange"}
set1.remove("banana")
print(set1)
Output:
{"apple", "mango", "orange"}
Clear items:
To clear the items or elements in the set we use the clear().
Example:
Input:
set1={"apple", "banana", "mango"}
set1.clear()
print(set1)
Output:
set1={}
Operations on sets:
Union :
Union operator is used add the elements in the two sets.
Example:
Input:
set1={1,2,3,4}
set1={2,4,5,6}
set1.union(set2)
Output:
{1,2,3,4,5,6}
Intersection:
Intersection operator is used to return the common elements in the two sets.
Example:
Input:
set1={1,2,3,4,5,6}
set2={3,4,7,8,9,1}
set1.intesection(set2)
Output:
{1,3,4}