If you look at the output of dataScientist and dataEngineer variables above, notice that the values in the set are not in the order added in. This is because sets are unordered. Sets containing values can also be initialized by using curly braces. Keep in mind that curly braces can only be used to initialize a set containing values. The image below shows that using curly braces without values is one of the ways to initialize a dictionary and not a set. To add or remove values from a set, you first have to initialize a set. You can use the method It is important to note that you can only add a value that is immutable (like a string or a tuple) to a set. For example, you would get a TypeError if you try to add a list to a set. There are a couple of ways to remove a value from a set. Option 1: You can use the The drawback of this method is that if you try to remove a value that is not in your set, you will get a KeyError. Option 2: You can use the The benefit of this approach over the Option 3: You can also use the It is important to note that the method raises a KeyError if the set is empty. You can use the The update method adds the elements from a set to a set. It requires a single argument that can be a set, list, tuples, or dictionary. The In the example, we have initialized three sets and used an update function to add elements from set2 to set1 and then from set3 to set1. Like many standard python data types, it is possible to iterate through a set. If you look at the output of printing each of the values in dataScientist, notice that the values printed in the set are not in the order they were added in. This is because sets are unordered. This tutorial has emphasized that sets are unordered. If you find that you need to get the values from your set in an ordered form, you can use the The code below outputs the values in the set dataScientist in descending alphabetical order (Z-A in this case). Part of the content in this section was previously explored in the tutorial 18 Most Common Python List Questions, but it is important to emphasize that sets are the fastest way to remove duplicates from a list. To show this, let's study the performance difference between two approaches. Approach 1: Use a set to remove duplicates from a list. The performance difference can be measured using the the Comparing these two approaches shows that using sets to remove duplicates is more efficient. While it may seem like a small difference in time, it can save you a lot of time if you have very large lists. A common use of sets in Python is computing standard math operations such as union, intersection, difference, and symmetric difference. The image below shows a couple standard math operations on two sets A and B. The red part of each Venn diagram is the resulting set of a given set operation. Python sets have methods that allow you to perform these mathematical operations as well as operators that give you equivalent results. Before exploring these methods, let's start by initializing two sets dataScientist and dataEngineer. A union, denoted dataScientist ∪ dataEngineer, is the set of all values that are values of dataScientist, or dataEngineer, or both. You can use the The set returned from the union can be visualized as the red part of the Venn diagram below. An intersection of two sets dataScientist and dataEngineer, denoted dataScientist ∩ dataEngineer, is the set of all values that are values of both dataScientist and dataEngineer. The set returned from the intersection can be visualized as the red part of the Venn diagram below. You may find that you come across a case where you want to make sure that two sets have no value in common. In order words, you want two sets that have an intersection that is empty. These two sets are called disjoint sets. You can test for disjoint sets by using the You can notice in the intersection shown in the Venn diagram below that the disjoint sets dataScientist and graphicDesigner have no values in common. A difference of two sets dataScientist and dataEngineer, denoted dataScientist \ dataEngineer, is the set of all values of dataScientist that are not values of dataEngineer. The set returned from the difference can be visualized as the red part of the Venn diagram below. A symmetric difference of two sets dataScientist and dataEngineer, denoted dataScientist △ dataEngineer, is the set of all values that are values of exactly one of two sets, but not both. The set returned from the symmetric difference can be visualized as the red part of the Venn diagram below. You may have previously have learned about list comprehensions, dictionary comprehensions, and generator comprehensions. There are also Python set comprehensions. Set comprehensions are very similar. Set comprehensions in Python can be constructed as follows: The output above is a set of 2 values because sets cannot have multiple occurrences of the same element. The idea behind using set comprehensions is to let you write and reason in code the same way you would do mathematics by hand. The code above is similar to a set difference you learned about earlier. It just looks a bit different. Membership tests check whether a specific element is contained in a sequence, such as strings, lists, tuples, or sets. One of the main advantages of using sets in Python is that they are highly optimized for membership tests. For example, sets do membership tests a lot more efficiently than lists. In case you are from a computer science background, this is because the average case time complexity of membership tests in sets are O(1) vs O(n) for lists. The code below shows a membership test using a list. Something similar can be done for sets. Sets just happen to be more efficient. Since If you had a value that wasn't part of the set, like A practical application of understanding membership is subsets. Let's first initialize two sets. If every value of the set You can check to see if one set is a subset of another using the method Since the method returns True in this case, it is a subset. In the Venn diagram below, notice that every value of the set You have have encountered nested lists and tuples. The problem with nested sets is that you cannot normally have nested Python sets, as sets cannot contain mutable values, including sets. This is one situation where you may wish to use a frozenset. A frozenset is very similar to a set except that a frozenset is immutable. You make a frozenset by using You can make a nested set if you utilize a frozenset similar to the code below. It is important to keep in mind that a major disadvantage of a frozenset is that since they are immutable, it means that you cannot add or remove values. The Python sets are highly useful to efficiently remove duplicate values from a collection like a list and to perform common math operations like unions and intersections. Some of the challenges people often encounter are when to use the various data types. For example, if you feel like you aren't sure when it is advantageous to use a dictionary versus a set, I encourage you to check out DataCamp's daily practice mode. If you any questions or thoughts on the tutorial, feel free to reach out in the comments below or through Twitter.dataScientist = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'}dataEngineer = {'Python', 'Java', 'Scala', 'Git', 'SQL', 'Hadoop'}
Add and Remove Values from Python Sets
# Initialize set with valuesgraphicDesigner = {'InDesign', 'Photoshop', 'Acrobat', 'Premiere', 'Bridge'}
Add Values to a Python Set
add
to add a value to a set.graphicDesigner.add('Illustrator')
graphicDesigner.add(['Powerpoint', 'Blender'])
Remove Values from Sets in Python
remove
method to remove a value from a set.graphicDesigner.remove('Illustrator')
discard
method to remove a value from a set.graphicDesigner.discard('Premiere')
remove
method is if you try to remove a value that is not part of the set, you will not get a KeyError. If you are familiar with dictionaries, you might find that this works similarly to the dictionary method get.pop
method to remove and return an arbitrary value from a set.graphicDesigner.pop()
Remove All Values from a Python Set
clear
method to remove all values from a set.graphicDesigner.clear()
Update Python Set Values
.update()
method automatically converts other data types into sets and adds them to the set.# Initialize 3 setsset1 = set([7, 10, 11, 13])set2 = set([11, 8, 9, 12, 14, 15])set3 = {'d', 'f', 'h'}# Update set1 with set2set1.update(set2)print(set1)# Update set1 with set3set1.update(set3)print(set1)
Iterate through a Python Set
# Initialize a setdataScientist = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'}for skill in dataScientist: print(skill)
Transform a Python Set into Ordered Values
sorted
function, which outputs a list that is ordered.type(sorted(dataScientist))
sorted(dataScientist, reverse = True)
Remove Duplicates from a List in Python
print(list(set([1, 2, 3, 1, 7])))
Approach 2: Use a list comprehension to remove duplicates from a list (If you would like a refresher on list comprehensions, see this tutorial).
def remove_duplicates(original): unique = [] [unique.append(n) for n in original if n not in unique] return(unique)print(remove_duplicates([1, 2, 3, 1, 7]))
timeit
library which allows you to time your Python code. The code below runs the code for each approach 10000 times and outputs the overall time it took in seconds.import timeit# Approach 1: Execution timeprint(timeit.timeit('list(set([1, 2, 3, 1, 7]))', number=10000))# Approach 2: Execution timeprint(timeit.timeit('remove_duplicates([1, 2, 3, 1, 7])', globals=globals(), number=10000))
Python Set Operations
dataScientist = set(['Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'])dataEngineer = set(['Python', 'Java', 'Scala', 'Git', 'SQL', 'Hadoop'])
union
union
method to find out all the unique values in two sets.# set built-in function uniondataScientist.union(dataEngineer)# Equivalent ResultdataScientist | dataEngineer
intersection
# Intersection operationdataScientist.intersection(dataEngineer)# Equivalent ResultdataScientist & dataEngineer
isdisjoint
method.# Initialize a setgraphicDesigner = {'Illustrator', 'InDesign', 'Photoshop'}# These sets have elements in common so it would return FalsedataScientist.isdisjoint(dataEngineer)# These sets have no elements in common so it would return TruedataScientist.isdisjoint(graphicDesigner)
Difference
# Difference OperationdataScientist.difference(dataEngineer)# Equivalent ResultdataScientist - dataEngineer
Symmetric Difference
# Symmetric Difference OperationdataScientist.symmetric_difference(dataEngineer)# Equivalent ResultdataScientist ^ dataEngineer
Set Comprehension
{skill for skill in ['SQL', 'SQL', 'PYTHON', 'PYTHON']}
{skill for skill in ['GIT', 'PYTHON', 'SQL'] if skill not in {'GIT', 'PYTHON', 'JAVA'}}
Membership Tests
# Initialize a listpossibleList = ['Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS', 'Java', 'Spark', 'Scala']# Membership test'Python' in possibleList
# Initialize a setpossibleSet = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS', 'Java', 'Spark', 'Scala'}# Membership test'Python' in possibleSet
possibleSet
is a set and the value 'Python'
is a value of possibleSet
, this can be denoted as 'Python'
∈ possibleSet
.'Fortran'
, it would be denoted as 'Fortran'
∉ possibleSet
.Subset
possibleSkills = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'}mySkills = {'Python', 'R'}
mySkills
is also a value of the set possibleSkills
, then mySkills
is said to be a subset of possibleSkills
, mathematically written mySkills
⊆ possibleSkills
.issubset
.mySkills.issubset(possibleSkills)
mySkills
is also a value of the set possibleSkills
.Frozensets
# Nested Lists and TuplesnestedLists = [['the', 12], ['to', 11], ['of', 9], ['and', 7], ['that', 6]]nestedTuples = (('the', 12), ('to', 11), ('of', 9), ('and', 7), ('that', 6))
frozenset()
.# Initialize a frozensetimmutableSet = frozenset()
nestedSets = set([frozenset()])
Conclusion
Python Sets Tutorial: Set Operations & Sets vs Lists (2025)
Table of Contents
Add and Remove Values from Python Sets
Add Values to a Python Set
Remove Values from Sets in Python
Remove All Values from a Python Set
Update Python Set Values
Iterate through a Python Set
Transform a Python Set into Ordered Values
Remove Duplicates from a List in Python
Python Set Operations
union
intersection
Difference
Symmetric Difference
Set Comprehension
Membership Tests
Subset
Frozensets
Conclusion
References
References
Top Articles
NEW Lot of 3 Unbranded Chrome Glitter Pigment Nail Mirror Powder, 6 Colours/pack
Fall Nail Colours with Glitter Your Information to Autumn Type - Hatchet
Nails & Art - Diamond Reflective Glitter
Latest Posts
Donald Trump Disses Taylor Swift During Eagles' White House Visit
Shimmer Your Nails with Metallic Powders
Recommended Articles
- you'd better not" versus "you'd better not to"
- Roczny kalendarz 2025 - Polska
- Naar huis met een blaaskatheter of suprapubische katheter (Folder)
- All Redeem Codes in June 2025 | Genshin Impact|Game8
- Netanyahu: We Have Set Back Iran's Nuclear Program Quite A Bit
- Spezial-Vibrator Test 2025 • Die 12 besten Spezial-Vibratoren im Vergleich - RTL Online
- [GA4] URL -bouwers: verzamel campagnegegevens met aangepaste URL's
- How Google Analytics works - Analytics Help
- Craz’ink Tattoo shop - 220 Bd Robert Ballanger, 93420 Villepinte, France
- Inside Maura Higgins' summer holiday makeup bag as huge new TV job is revealed
- Psoriasis - Diagnosis and treatment
- Neo Geo Pocket Color "Unlocked" Save Patches.
- Professional Nail Drill Bits Set for Manicures & Pedicures
- Coronavirus Hong Kong
- ISOLATED definition and meaning | Collins English Dictionary
- Gefrierschränke online kaufen | Effizient & geräumig | Real-Markt.de
- Forum 60 millions de consommateurs • Consulter le sujet
- common, adj. & adv. meanings, etymology and more
- Using Overnight Hand Moisturizing Gloves: A Treat for Both Skin and Nails
- Top 20 Best Banda Bands - MusicalHow
- healthier or more healthy?
- Weber Servicebetriebsanleitungen | Weber Grill Original
- Google Drive for Desktop verwenden
- Das WOW Premium Abo für ein besseres Streaming-Erlebnis
- Men's Clothes | Men's Fashion | SELECTED
- How to sign in to Hotmail
- Understanding Creatinine Normal Levels: What Do They Mean for Your Kidney Health?
- [FR] PokeMMO Pour Les Nuls
- Resmed AirFit X30i Oral Nasal CPAP Mask
- Mercado: veja as notícias que movimentaram o Bahia na semana
- "I've known him since" or "I know him since"?
- G | History, Etymology, & Pronunciation | Britannica
- I recommend to do / doing something
- Back up & sync device & SIM contacts
- Download og installer Google Chrome - Computer
- a quick cut or an express haircut
- Sweet Temptation Tattoo-Studio in Bottrop | bei Tattoola.de
- La Colors Gel Polish: Application Tips And Tricks
- How to Nail Dip Powder: The Ultimate Guide to a Long-Lasting Manicure
- Itchy nose ! CPAP Forums
- KTV - Gò Vấp - Tổng hợp KTV Spa Aroma
- Ski Alpin: Alpine Ski-Wettbewerbe und etablierte Rennstrecken
- on / in / at the top-right corner
- Hoe maak je Koji-rijst thuis [Volledig recept]
- Salg til Færøerne - moms
- R Tutorial | Learn R Programming - GeeksforGeeks
- right-hand corner and right corner
- Presión arterial baja (hipotensión) - Síntomas y causas
- Ms Pacman won't power on - power supply and fuse questions
- 10 anime with classification +18 to watch at Crunchyroll
- Consulter vos messages sur votre ordinateur ou votre tablette Android
- API | Backstage Software Catalog and Developer Platform
- Other ways of saying he is "whipped"
- ≥ Meridian Audioapparatuur Beschikbaar | Marktplaats
- OSTOMY DEFINED | Ostomy Foundation
- Programmi Italia 1 Oggi
- CBD: Safe and effective?
- Kein absolutes minimum und keine qualität ist Von backup abhängig.
- Test de débit internet : vérifiez la vitesse de votre connexion fibre ou ADSL
- Glucose là gì? Vai trò của glucose đối với cơ thể con người
- Purple Toothpaste for Teeth Whitening
- in the morning/ at the morning/ at morning
- Blood in urine (hematuria) - Symptoms and causes
- St. Patrick's Day March 6 - March 28
- Body's & Bodystockings Kopen? (40+ Keuzes) Shop Nu
- Best Hair Loss Treatments for Men: 7 Solutions That Actually Work in 2025
- Aaron Paul's Net Worth 2024, Breaking Bad Salary (FORBES)
- The Eyes (Human Anatomy): Diagram, Function, Definition, and Eye Problems
- [GA4] About events - Analytics Help
- Money blog: 'I get paid to cuddle babies and help hundreds of women give birth - this is my best advice for expectant parents'
- Start a YouTube TV free trial
- Fazer o download e instalar o Google Chrome - Computador
- Install and manage extensions - Chrome Web Store Help
- Can eating certain foods help improve your cholesterol levels?
- Merlyn Truestone Square Shower Tray
- What is Digital? | Definition from TechTarget
- Predatory Sparrow: The pro-Israel group that stole $90 million from Iran's biggest crypto exchange
- Adoption Center on Toyhouse
- The True Story Behind David Bowie And Bob Dylan's Relationship - Grunge
- rip someone a new one
- The role of scrubs in identifying healthcare professionals
- Bois Dauphin Perfect. - Ping Pong et Tennis de Table
- Politie - Klantenservicecontact.nl
- Anregende Massagegriffe für Po und Hüften
- MIZHSE 9D Cat Eye Gel Nail Polish, Pink Magnetic Gel Polish with Magnet Stick, Magic Shimmer Galaxy Effect Holographic Glitter Silky Cat Eye Nail Polish Soak Off Nail Art Salon Manicure DIY at Home
- IMAGION BIOSYSTEMS LIMITED IBX(ASX) - ASX Stock Market Charts & Financials
- FR/EN: guillemets (« ») / quotation marks (“ ”) - usage & punctuation
- GAMMA | Dremel multitools kopen?
- Comment se prononce la lettre Q en français ?
- Master di secondo livello
- Blood pressure chart: What your reading means
- Find Best Hair Salon Near Me In Duncanville, AL | Vagaro
- Find lost photos & videos - Computer
- Zo typ je alle accenten op de 'o' in Windows 10 2020 (dodentoetsmethodes + alt-codes) / Windows dodentoetsmethodes + altcodes | AlleKennis.nl
- OLED TV | TVs 4K mais recentes | Samsung Brasil
- T definition and meaning | Collins English Dictionary
- Skin Type Chart: Determine Your Skin Type and Build a Skincare Routine
- Wat zijn de principes van bio?
- twin + double + full + queen + king (colchones)
- in the party, on the party
Article information
Author: Manual Maggio
Last Updated:
Views: 5963
Rating: 4.9 / 5 (69 voted)
Reviews: 92% of readers found this page helpful
Author information
Name: Manual Maggio
Birthday: 1998-01-20
Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242
Phone: +577037762465
Job: Product Hospitality Supervisor
Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis
Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.