Sets In Python

Sets

You are lying if you say, that you are hearing sets for the first time. A set is a well-defined collection of objects. In Python, Set is enclosed within the Curly brackets {}. But wait a minute, didnâ€™t we just discuss in the last article, that Dictionary is enclosed within Curly Brackets. Set also is enclosed within the curly brackets the difference is that Set has no key-value pair separated with a colon(:). But when you initialize the empty {} by default Python will take {} as Dictionary data type.

check = {}
type(check)

check = set()
type(check)

Output:
<class 'dict'>
<class 'set'>
dict_eg = {"I am key":"I am value"}
print(dict_eg,'\n',type(dict_eg))
{'I am key': 'I am value'}
set_eg = {"I am element"}
print(set_eg,'\n',type(set_eg))
{'I am element'}

You might be fed up with seeing len(), count(), clear(), in and not in methods. This concept is used in Set as well but we wonâ€™t be repeating it. I assume you are well familiar with those concepts. Besides that, Set is a very useful data type and we will be discussing most of the Set methods. If you are familiar with len(), count(), clear() methods check articles on Tuple, List, Dictionary, and String.

Set Methods

add is used to insert a new element in the set.

{'Yumeko', 'Hinata', 'Zero Two', 'Makise', 'Mai'}
{'Makise', 'Zero Two', 'Mai', 'Mikasa', 'Hinata', 'Violet', 'Yumeko'}
setAB = set(range(1,20,2))
setAB
{1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
setAB
{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21}
TypeError: add() takes exactly one argument (2 given)
TypeError: unhashable type: 'set'

2. copy

anime_content = {"Opening","Plot","Fun","Emotions","Lesson","Ending"}
a_copy = anime_content
a_copy
{'Ending', 'Emotions', 'Fun', 'Lesson', 'Plot', 'Opening'}
anime_content
{'Ending', 'Emotions', 'Fun', 'Lesson', 'Plot', 'Opening'}
anime_content
{'True Happiness', 'Ending', 'Emotions', 'Fun', 'Lesson', 'Plot', 'Opening'}
a_copy
{'True Happiness', 'Ending', 'Emotions', 'Fun', 'Lesson', 'Plot', 'Opening'}
a_copy.remove("Fun") #we will discuss above remove soon.
a_copy
{'True Happiness', 'Ending', 'Emotions', 'Leason', 'Plot', 'Opening'}
anime_content
{'True Happiness', 'Ending', 'Emotions', 'Leason', 'Plot', 'Opening'}

When we assign a set variable to a new variable. It creates a clone of the existing set variable. Say anime_content is the original variable and a_copy is the clone of that set variable. If you make any changes in anime_content, it will reflect back in a_copy as well. Vice-versa is also true, if you make any changes in a_copy it will reflect back in anime_content as well.

But what if you want to modify a new variable without affecting the original variable, you can use the copy method.

a1_copy = anime_content.copy()
a1_copy
{'True Happiness', 'Plot', 'Ending', 'Opening', 'Emotions', 'Lesson'}
anime_content
{'Ending', 'Opening', 'Lesson', 'True Happiness', 'Plot', 'Emotions'}
a1_copy
{'True Happiness', 'Plot', 'Ending', 'Opening', 'Emotions', 'Extra', 'Lesson'}
anime_content
{'Ending', 'Opening', 'Lesson', 'True Happiness', 'Plot', 'Emotions'}

Once you have created a copy of the set variable, the changes in the new set will not reflect in the original set.

3. union and intersection

The union of two sets A and B is represented by A âˆª B. This is the set of all different elements that are included in A or B.

The intersection of two sets A and B is represented by A âˆ© B. This is the set of all different elements that are included in both A and B.

A = {1,2,3}
B = {2,3,5,7}
A.union(B)
{1, 2, 3, 5, 7}
A.intersection(B)
{2, 3}
R = {'a','b','c','d'}
Q = {'g','h','i','j'}
R.union(Q)
{'h', 'g', 'j', 'b', 'a', 'c', 'd', 'i'}
Q.union(R)
{'h', 'g', 'j', 'b', 'a', 'c', 'd', 'i'}
R.intersection(Q)
set()
len(R.intersection(Q))
0

4. pop

Well I know I said mentioned earlier no method will be repeated again. But here pop does completely different than what we saw earlier.

num = set(range(34,50))
num
{34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49}
num.pop()
34
num
{35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49}

In sets pop removes the starting element(index=0) instead of ending element(index=-1).

5. issubset and issuperset

If B is a subset of A, then B is contained in A. That means whatever elements are in set B, those elements are found in set A as well. Since set B contains only a few elements of set A, it is termed as a subset of A. With A being the superset. For example, India is a superset, and Bangalore, Mumbai is a subset of it. Anime is a superset and One Piece is a subset of it.

a = set(range(10,20)) #10,11,12,â€¦..,19
b = set(range(5,12)) #5,6,7,â€¦,11
b.issubset(a)
False
b = set(range(10,12)) #10,11
b.issubset(a)
True
b.issuperset(a)
False
a.issuperset(b)
True

Difference Between Discard and Remove Methods In Set?

We have discussed five-set methods already. But we didnâ€™t deal with removing specific elements. Sets provide two such methods remove and discard which are used to remove specific elements from the sets.

setA = set(range(10))
setA
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

Let us delete some elements from the set using remove and discard methods.

setA.remove(3) #3 exists and it will be removed
setA
{0, 1, 2, 4, 5, 6, 7, 8, 9}
setA.remove(2) #2 exists and it will be removed
setA
{0, 1, 4, 5, 6, 7, 8, 9}
setA.discard(9) #9 exists and it will be removed
setA
{0, 1, 4, 5, 6, 7, 8}
setA.discard(5) #5 exists and it will be removed
setA
{0, 1, 4, 6, 7, 8}

Both remove and discard methods remove the existing elements from the set. But here are the example of why there are different.

print(setA.remove(11)) #returns KeyError
KeyError: 11
None
print(setA.remove(12)) #returns KeyError
KeyError: 12
None

remove() and discard() methods perform the same task when they delete existing element/key from the set. But when the elements do not exist in the set. Then remove() returns KeyError whereas discard() returns None.

Why Set Is Different?

Set canâ€™t be indexed. Besides that, it shuffles the string of elements randomly.

red_hair_pirates = {"Shanks","Beckman","Yasopp","Roux"}
red_hair_pirates
{'Beckman', 'Shanks', 'Roux', 'Yasopp'}
red_hair_pirates[0]
TypeError: 'set' object is not subscriptable

Set has no fixed order, you can observe that in the above example: the executed set elements are different from that of assigned set elements.

Conclusion

You can try 30 Days Python Programming by solving amazing code daily. Anime Vyuh Github Organization has a public repo, which will help you with 30 Days Of Python.

Check Out The Previous Tutorials Part On Learn Python.

If you like our content, support us by Buying a Coffee.