Sets in Python
Sets
Sets are the collection of unordered elements that are unique. If the data is repeated more than one time, it would be entered into the set only once.
Creating a Set
Sets are created using curly braces but instead of adding key-value pairs you just pass values to it.
# Create a set with duplicate values
my_set = {1, 2, 3, 4, 5, 3, 2, 5}
print(my_set)
# Output:
# {1, 2, 3, 4, 5}
Note: Notice how duplicate values (3, 2, 5) are automatically removed in the output.
Adding Elements
To add elements, you use the add() function and pass the value to it.
my_set = {1, 2, 3}
my_set.add(4) # add element to set
print(my_set)
# Output:
# {1, 2, 3, 4}
Operations in Sets
The different operations on set such as union, intersection and so on are shown below:
my_set = {1, 2, 3, 4}
my_set_2 = {3, 4, 5, 6}
print(my_set.union(my_set_2))
print(my_set.intersection(my_set_2))
print(my_set.difference(my_set_2))
print(my_set.symmetric_difference(my_set_2))
my_set.clear()
print(my_set)
# Output:
# {1, 2, 3, 4, 5, 6}
# {3, 4}
# {1, 2}
# {1, 2, 5, 6}
# set()
- Union() function combines data present in both sets.
- Intersection() function finds data present in both sets.
- Difference() function deletes data present in both and outputs data present only in set.
- Symmetric_difference() function does same as difference() function but outputs data which is remaining in both sets.