3 3-Sets
3 3-Sets
ipynb - Colab
keyboard_arrow_down Sets
Sets are a built-in data type in Python used to store collections of unique items. They are unordered, meaning that the elements do not follow a
specific order, and they do not allow duplicate elements. Sets are useful for membership tests, eliminating duplicate entries, and performing
mathematical set operations like union, intersection, difference, and symmetric difference.
##create a set
my_set={1,2,3,4,5}
print(my_set)
print(type(my_set))
{1, 2, 3, 4, 5}
<class 'set'>
my_empty_set=set()
print(type(my_empty_set))
<class 'set'>
my_set=set([1,2,3,4,5,6])
print(my_set)
{1, 2, 3, 4, 5, 6}
my_empty_set=set([1,2,3,6,5,4,5,6])
print(my_empty_set)
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 4, 5, 6, 7}
my_set.remove(10)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[11], line 1
----> 1 my_set.remove(10)
KeyError: 10
my_set.discard(11)
print(my_set)
{1, 2, 4, 5, 6, 7}
## pop method
removed_element=my_set.pop()
print(removed_element)
print(my_set)
1
{2, 4, 5, 6, 7}
https://colab.research.google.com/drive/1XO6DpAQq70vhjJ6w2Ut5JR4zeUCiVgGL#printMode=true 1/3
7/18/24, 9:36 AM 3.3-Sets.ipynb - Colab
## clear all the elements
my_set.clear()
print(my_set)
set()
True
False
## MAthematical Operation
set1={1,2,3,4,5,6}
set2={4,5,6,7,8,9}
### Union
union_set=set1.union(set2)
print(union_set)
## Intersection
intersection_set=set1.intersection(set2)
print(intersection_set)
set1.intersection_update(set2)
print(set1)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{4, 5, 6}
{4, 5, 6}
set1={1,2,3,4,5,6}
set2={4,5,6,7,8,9}
## Difference
print(set1.difference(set2))
{1, 2, 3}
set1
{1, 2, 3, 4, 5, 6}
set2.difference(set1)
{7, 8, 9}
## Symmetric Difference
set1.symmetric_difference(set2)
{1, 2, 3, 7, 8, 9}
## Sets Methods
set1={1,2,3,4,5}
set2={3,4,5}
## is subset
print(set1.issubset(set2))
print(set1.issuperset(set2))
False
True
lst=[1,2,2,3,4,4,5]
set(lst)
{1, 2, 3, 4, 5}
https://colab.research.google.com/drive/1XO6DpAQq70vhjJ6w2Ut5JR4zeUCiVgGL#printMode=true 2/3
7/18/24, 9:36 AM 3.3-Sets.ipynb - Colab
### Counting Unique words in text
unique_words=set(words)
print(unique_words)
print(len(unique_words))
keyboard_arrow_down Conclusion
Sets are a powerful and flexible data type in Python that provide a way to store collections of unique elements. They support various operations
such as union, intersection, difference, and symmetric difference, which are useful for mathematical computations. Understanding how to use
sets and their associated methods can help you write more efficient and clean Python code, especially when dealing with unique collections
and membership tests.
https://colab.research.google.com/drive/1XO6DpAQq70vhjJ6w2Ut5JR4zeUCiVgGL#printMode=true 3/3