Sets In Python: No Duplicates Allowed

Do you have a number of trophies🏆🥉🥋🏸🏏🥇🎾🥍🏓🏒🏑🎮🎲🥅📰/certificates/achievements/medals?

Even if the answer is no you’ll soon have a large number of them because I know that you are always eager to learn something new just like me.

And that is why you are here today to store all of them in python sets and do some fun operations with them. (Future trophies if not yet there and current trophies if there)

Sets in python official documentation.

Previous post’s challenge’s solution

done = """
⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⣿⣿⣷⣶⣴⣾⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣀⣤⣤⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣤⣤⣤⣄⠀⠀⠀⠀
⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀⠀
⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠈⢻⣿⣿⣿⣿⣿⣿⣿
⢿⣿⣿⣿⣿⣿⣿⣿⡿⠻⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿
⢈⣿⣿⣿⣿⣿⣿⣯⡀⠀⠈⠻⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⡁
⣾⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⠈⠛⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⠈⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀
⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀
⠀⠀⠀⠀⠉⠛⠛⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠛⠛⠉⠁⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⠿⢿⡻⠿⣿⣿⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀
"""
print(done)

name_homework_done = {"Liam": ("Yes", "No", "Yes"),
                      "Olivia": ("Yes", "No", "Yes"),
                      "Noah": ("Yes", "Yes", "Yes"),
                      "Emma": ("Yes", "No", "Yes")}
print(name_homework_done)

Output:-

⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⣿⣿⣷⣶⣴⣾⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣀⣤⣤⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣤⣤⣤⣄⠀⠀⠀⠀
⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀⠀
⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠈⢻⣿⣿⣿⣿⣿⣿⣿
⢿⣿⣿⣿⣿⣿⣿⣿⡿⠻⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿
⢈⣿⣿⣿⣿⣿⣿⣯⡀⠀⠈⠻⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⡁
⣾⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⠈⠛⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⠈⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀
⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀
⠀⠀⠀⠀⠉⠛⠛⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠛⠛⠉⠁⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⠿⢿⡻⠿⣿⣿⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀

{'Liam': ('Yes', 'No', 'Yes'), 'Olivia': ('Yes', 'No', 'Yes'), 'Noah': ('Yes', 'Yes', 'Yes'), 'Emma': ('Yes', 'No', 'Yes')}

I think the code and output are self-explanatory but comment below if you have a doubt.

What are sets?

Sets in python are simply an unordered, unique, and unindexed collection of items.

This means that the data that we store in sets are not stored in any particular sequence. Also, no repetition of elements is allowed in a set. Along with this, you cannot access the elements of a set using indexes because they don’t have any index.

You can only access data in a set by printing the set, or by using a loop. (we will discuss loops in later posts) The keyword “in” is used to check the presence of an element in a set.

** Sets are mutable objects but the elements in them are of immutable data type.

Creating sets

There are majorly 2 ways to create a set in python:-

First, by putting values in a comma-separated sequence inside curly brackets. Like the one below:-

trophies = {"Music championship", "Coding Championship", \
    "Certified Associate in Python Programming (PCAP)", \
    "CompTIA Security+", \
    "MongoDB Certified Developer Associate Exam"}

print(trophies)
print(type(trophies))

Output:-

{'CompTIA Security+', 'Coding Championship', 'Certified Associate in Python Programming (PCAP)', 'Music championship', 'MongoDB Certified Developer Associate Exam'}
<class 'set'>

Second, by using the set function for this purpose:-

trophies = set(("Music championship", "Coding Championship", \
    "Certified Associate in Python Programming (PCAP)", \
    "CompTIA Security+", \
    "MongoDB Certified Developer Associate Exam"))

print(trophies)
print(type(trophies))

Output:-

{'Music championship', 'MongoDB Certified Developer Associate Exam', 'Certified Associate in Python Programming (PCAP)', 'CompTIA Security+', 'Coding Championship'}
<class 'set'>

Remember that you can only give data inside the set function in form of a list, tuple, or string. If you try to give it in any other form like this then you will get a TypeError.

trophies = set("Music championship", "Coding Championship", \
    "Certified Associate in Python Programming (PCAP)", \
    "CompTIA Security+", \
    "MongoDB Certified Developer Associate Exam")

print(trophies)
print(type(trophies))

Output:-

Traceback (most recent call last):
File "c:\Desktop\python-hub.com\setsInPython.py", line 1, in
trophies = set("Music championship", "Coding Championship", \
TypeError: set expected at most 1 argument, got 5

Creating An Empty Set

Now let us say you want an empty set to store your future achievements🏆. Here’s how you can do that:-

Future_achievements = set()
print(Future_achievements)
print(type(Future_achievements))

Output:-

set() 
<class 'set'>

What? Are you saying that we can do this simply by using curly brackets? Ok, as you say let’s do it.

Future_achievements = {}
print(Future_achievements)
print(type(Future_achievements))

Output:-

{}
<class 'dict'>

Oh no we wanted a set but got a dictionary. Why?🤔

Because these curly brackets are reserved for making an empty dictionary in python. You cannot snatch the dictionary’s right away from it.

Not fair, after all, it helped you out with your shop.😜🤘

Modifying Sets

You must be wondering what if any of these happens to me:-

  • I got a new achievement and want to add it;🏆
  • I have more than one achievements to add; or
  • Due to some mischief, my mom took away some of my certificates.😓

No need to worry here’s what you will do in such situations.

Add Elements

When you get a new achievement celebrate. And then just use add function to add your achievement to your set:-

trophies = set(("Music championship", "Coding Championship", \
    "Certified Associate in Python Programming (PCAP)", \
    "CompTIA Security+", \
    "MongoDB Certified Developer Associate Exam"))
trophies.add("new achievement")
print(trophies)

Output:-

{'Music championship', 'Coding Championship', 'CompTIA Security+', 'Certified Associate in Python Programming (PCAP)', 'MongoDB Certified Developer Associate Exam', 'new achievement'}

Update Set

To add more than one of your achievements use update functions:-

trophies.update(["a1", "a2", "prankster of the year"])
print(trophies)

Output:-

{'new achievement', 'Coding Championship', 'Certified Associate in Python Programming (PCAP)', 'a1', 'MongoDB Certified Developer Associate Exam', 'prankster of the year', 'Music championship', 'a2', 'CompTIA Security+'}

Delete Set

To delete any of them you have two options use either the discard function or the remove function. The only difference between the two is:-

discard() leaves the set as it is if the element you entered to delete is not present in the set. remove() on the other hand, raises an error.

# Using discard
print(f"before discard: {trophies}")
trophies.discard("a1")
print(f"\nafter discard: {trophies}")
trophies.discard("a1")  #Doesn't produce any errors

Output:-

before discard: {'a1', 'Coding Championship', 'prankster of the year', 'Certified Associate in Python Programming (PCAP)', 'Music championship', 'a2', 'new achievement', 'CompTIA Security+', 'MongoDB Certified Developer Associate Exam'}

after discard: {'Coding Championship', 'prankster of the year', 'Certified Associate in Python Programming (PCAP)', 'Music championship', 'a2', 'new achievement', 'CompTIA Security+', 'MongoDB Certified Developer Associate Exam'}

# Using remove
print(f"before remove: {trophies}")
trophies.remove("a2")
print(f"\nafter remove: {trophies}")
trophies.remove("a2")  #raises a key error

Output:-

before remove: {'Coding Championship', 'a2', 'Certified Associate in Python Programming (PCAP)', 'CompTIA Security+', 'prankster of the year', 'MongoDB Certified Developer Associate Exam', 'Music championship', 'new achievement'}

after remove: {'Coding Championship', 'Certified Associate in Python Programming (PCAP)', 'CompTIA Security+', 'prankster of the year', 'MongoDB Certified Developer Associate Exam', 'Music championship', 'new achievement'}
Traceback (most recent call last):
  File "c:\Desktop\python-hub.com\setsInPython.py", line 5, in <module>
    trophies.remove("a2")  #raises an error
KeyError: 'a2'

Operations And Methods On Sets

Sets support a number of mathematical operations like union, intersection, difference, and symmetric difference. There are a lot more of them however, these are the majorly used ones.

For understanding these functions we will use the following sets to keep the code simple:-

t = {1, 2, 3, 4, 5}
t2 = {4, 5, 6, 7, 8}

Say t stores your trophies and t2 your friend’s trophies.

Set Union

Union would give you a set having all the trophies of yours and your friend’s. However, it will only store the common trophies once because sets do not allow one element twice.

You can either perform union using the "|" operator. Or using the union function.

sets union
t = {1, 2, 3, 4, 5}
t2 = {4, 5, 6, 7, 8}

print(t | t2)
print(t.union(t2))

Output:-

{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}

Set Intersection

The intersection will give you a set of the trophies you and your friend have in common. For this, you can either use the "&" operator or can use the intersection function.

Set Intersection
t = {1, 2, 3, 4, 5}
t2 = {4, 5, 6, 7, 8}

print(t & t2)
print(t.intersection(t2))

Output:-

{4, 5}
{4, 5}

Set Difference

The difference will give a set of your trophies which are different from that of your friend. Or your friend’s trophies that are different from yours. For this, you can either use "-" operator or the difference function.

Set Difference
t = {1, 2, 3, 4, 5}
t2 = {4, 5, 6, 7, 8}

print(t - t2) #only your trophies that are different from your friend
print(t2 - t) #only friend's trophies that are different from yours
print()
print(t.difference(t2)) #only your trophies that are different from your friend
print(t2.difference(t)) #only friend's trophies that are different from yours

Output:-

{1, 2, 3}
{8, 6, 7}

{1, 2, 3}
{8, 6, 7}

Set Symmetric Difference

The symmetric difference will give a set having all the trophies of both of you except the ones in common. For this, you can either use the "^" operator or can use the symmetric_difference function.

Set Symmetric Difference
t = {1, 2, 3, 4, 5}
t2 = {4, 5, 6, 7, 8}

print(t ^ t2)
print(t.symmetric_difference(t2))

Output:-

{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}

Frozen Sets(A New Datatype)

It is a new data type in python. It has all the properties of sets but the only difference is that they are unchangeable. Just imagine this as you are sure with these achievements never being obsolete. (Like walking🚶‍♀️😜 ok bad joke but you got the point)

Frozen sets can be also used as dictionary keys because they are immutable. You can create them simply by using the frozenset() function.

frozen_trophies = frozenset(["Music championship", "Coding Championship", \
    "Certified Associate in Python Programming (PCAP)", \
    "CompTIA Security+", \
    "MongoDB Certified Developer Associate Exam", \
    "new achievement",  "prankster of the year"])

print(frozen_trophies)
print(type(frozen_trophies))

Output:-

frozenset({'Coding Championship', 'Certified Associate in Python Programming (PCAP)', 'new achievement', 'Music championship', 'CompTIA Security+', 'prankster of the year', 'MongoDB Certified Developer Associate Exam'})
<class 'frozenset'>

Conclusion

In this post, we saw how can we store all our achievements in a python set. And how can create a python set to store our future achievements? Also, how can we use it for having fun competitions with our friends? Finally, we saw a new data type frozen set.

Challenge🧗‍♀️

Just today a person 🦹‍♂️ from the fun world came to you to ask for help. He needs a fun world dictionary📖 that will include at least 5 words(can be your own or real ones) and give your own meaning to these words. This dictionary should allow users to input a word to search for its meaning.

Your challenge today is to create a funny🤣 dictionary for the fun world man🦹‍♂️.

You will need to use the conditional statement if for this purpose.

It should look something like this(You can show your own creativity🛠):-

Dictionary in python a challenge

Do give it a try you’ll love it for sure.

I know that this challenge has nothing to do with sets but it will be really useful to solve this challenge now. So with your kind agreement(I assume you agreed please do 🙇‍♀️), we will do a challenge on sets some other day.

Go fast. I am waiting. Comment your answers below.

This was it for the post. Comment below suggestions if there and tell me whether you liked it or not. Do consider sharing this with your friends.

See you in the next post till then have a great time.😊

This Post Has 2 Comments

  1. Bryon Ailsworth

    Way cool! Some extremely valid points! I appreciate you penning this post plus the rest of the website is also really good.

  2. Maitry

    Thanks a lot, Bryon Ailsworth, Glad to know you liked it! Stay tuned for more of such content.

Comments are closed.