Python Sets

JK 2014 
Created at
Updated at  
7,077 0 0

Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

thisset = {"apple", "banana", "cherry"}
print(thisset)

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.


Unordered

Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred to by index or key.


Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has been created.


Duplicates Not Allowed

Sets cannot have two items with the same value.

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)
thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)
thisset = {"apple", "banana", "cherry", False, True, 0}

print(thisset)

Get the Length of a Set

To determine how many items a set has, use the len() function.

thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Set Items - Data Types

Set items can be of any data type:

set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

A set can contain different data types:

set1 = {"abc", 34, True, 40, "male"}

type()

From Python's perspective, sets are defined as objects with the data type 'set':

myset = {"apple", "banana", "cherry"}
print(type(myset))

 

The set() Constructor

It is also possible to use the set() constructor to make a set.

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)

Access Items

You cannot access items in a set by referring to an index or a key.

But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)

Check if "banana" is present in the set:

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Add Items

To add one item to a set use the add() method.

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

Add Sets

To add items from another set into the current set, use the update() method.

thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)

Add Any Iterable

The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).

thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)

Remove Item

To remove an item in a set, use the remove(), or the discard() method.

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)
thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)

Loop Items

You can loop through the set items by using a for loop:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)

Join Two Sets

There are several ways to join two or more sets in Python.

You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

Keep ONLY the Duplicates

The intersection_update() method will keep only the items that are present in both sets.

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.intersection_update(y)

print(x)

The intersection() method will return a new set, that only contains the items that are present in both sets.

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.intersection(y)

print(z)

Keep All, But NOT the Duplicates

The symmetric_difference_update() method will keep only the elements that are NOT present in both sets.

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.symmetric_difference_update(y)

print(x)

The symmetric_difference() method will return a new set, that contains only the elements that are NOT present in both sets.

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.symmetric_difference(y)

print(z)
x = {"apple", "banana", "cherry", True}
y = {"google", 1, "apple", 2}

z = x.symmetric_difference(y)

print(z)

Set Methods

Python has a set of built-in methods that you can use on sets.

MethodDescription
add()Adds an element to the set
clear()Removes all the elements from the set
copy()Returns a copy of the set
difference()Returns a set containing the difference between two or more sets
difference_update()Removes the items in this set that are also included in another, specified set
discard()Remove the specified item
intersection()Returns a set, that is the intersection of two other sets
intersection_update()Removes the items in this set that are not present in other, specified set(s)
isdisjoint()Returns whether two sets have a intersection or not
issubset()Returns whether another set contains this set or not
issuperset()Returns whether this set contains another set or not
pop()Removes an element from the set
remove()Removes the specified element
symmetric_difference()Returns a set with the symmetric differences of two sets
symmetric_difference_update()inserts the symmetric differences from this set and another
union()Return a set containing the union of sets
update()Update the set with the union of this set and others
Tags Python Python Sets Facebook X
Comments 0
Similar posts
  1. Python Tuples
    7,154
  2. Python Dictionaries
    7,042
  3. Python Comparison Operators
    7,230
  4. Python Arithmetic Operators
    7,063
  5. Printing string n times
    7,055
  6. String concatenation by join()
    7,125
  7. Python Conditions and If statements
    7,120
  8. Python Lists
    7,322
  9. Python String Operations
    7,394
  10. Python Data Types
    7,420
  11. Python While Loops/For Loops
    7,485
  12. Python Functions
    7,054
  13. Python Variables
    7,380
  14. Python Comments
    7,514
  15. Python Syntax
    7,393
  16. Python Lambda
    7,094
  17. Python Arrays
    7,077
  18. Python Classes/Objects
    7,445
  19. Python Getting Started
    7,438
  20. Python Introduction
    7,089
  21. What is Python?
    7,701
  22. Python Inheritance
    7,181
  23. Python Iterators
    7,094
  24. Python Polymorphism
    7,073
  25. Python Scope
    7,054
  26. Python Modules
    7,079
  27. Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering
    7,350
  28. Machine Learning Types and Programming Languages
    7,221
  29. Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship
    7,867
  30. Mastering Excel Data Manipulation with Python
    7,055
  31. Challenge: One Code Problem Per Day
    1,072
  32. Clean Python Environments: The Power of venv vs. Docker
    811
  1. Python code to convert from Lunar to Solar
    7,698
  2. Python example to download webpage
    8,560
  3. Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship
    7,867
  4. Python Modules
    7,079
  5. Python Scope
    7,054
  6. Python Polymorphism
    7,073
  7. Python Iterators
    7,094
  8. Python Inheritance
    7,181
  9. Python Classes/Objects
    7,445
  10. Python Arrays
    7,077
  11. Python Lambda
    7,094
  12. Python Functions
    7,054
  13. Python While Loops/For Loops
    7,485
  14. Python Conditions and If statements
    7,120
  15. Python Dictionaries
    7,042
  16. Python Tuples
    7,154
  17. Python Comparison Operators
    7,230
  18. Python Arithmetic Operators
    7,063
  19. Printing string n times
    7,055
  20. String concatenation by join()
    7,125
  21. Python Lists
    7,322
  22. Python String Operations
    7,394
  23. Python Data Types
    7,420
  24. Python Variables
    7,380
  25. Python Comments
    7,514
  26. Python Syntax
    7,393
  27. Python Getting Started
    7,438
  28. Python Introduction
    7,089
  29. What is Python?
    7,701
Recently updated
  1. Michael Jackson's Billie Jean
    46
  2. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    111
  3. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    313
  4. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    208
  5. The Evolution and Production Reality of Agentic AI
    191
  6. How to Activate or Waive Your UIUC Student Health Insurance
    272
  7. Complete Guide to Building a Machine Learning Model
    313
  8. My life cuts at Las Vegas during Thanksgiving day holiday
    7,393
  9. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    338
  10. Harness vs. OpenClaw: Two Very Different "Agents"
    945
  11. Clean Python Environments: The Power of venv vs. Docker
    811
  12. What is Docker? Why is Docker also useful in a development environment?
    607
  13. UIUC 2026-2027 Academic Calendar
    1,554
  14. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    796
  15. Open-Source LLMs: The AI Revolution
    740
  16. Resume 2.0: Leveling Up for My First Software Gig
    2,173
  17. Not everyone will understand what this man just did
    1,806
  18. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,574
  19. Unpacking IU's Shopper
    742
  20. Jackie Chan's Police Story: The Action Masterpiece
    640
  21. The IVE Story: Identity, 'I AM' Charts, and Influence
    944
  22. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,177
  23. Open Databases for Sex Crime Occurrences in the U.S.
    704
  24. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,590
  25. My First Day at University of Illinois-Urvana Champaign
    1,178
  26. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,113
  27. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,192
  28. Sipping the Stars: My Starbucks Adventure
    9,622
  29. Exciting explore at Sequoia National Park
    7,638
  30. My Life Shot at Death Valley
    1,678
  31. Ip Man fights with Muay Thai Master
    925
  32. Mad Clown - Don't Die
    1,006
  33. How to get Student Enrollment and Degree Verification at UIUC
    4,778
  34. LAX Thanksgiving Rush: A Joyful Reunion
    914
  35. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,107
  36. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    967
  37. 10CM - To Reach You (너에게 닿기를)
    1,150
  38. Feeling weak? Transform yourself at the UIUC ARC!
    1,566
  39. BOYNEXTDOOR - If I Say I Love You
    1,178
  40. The Future of Software Engineer - AI Engineering
    923
  41. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    897
  42. Lie - Legend song by BIGBANG
    7,807
  43. Why ROLLBACK is useful when you work with Google Gemini CLI?
    820
  44. Reimbursement after Vaccination at McKinley Health Center
    1,011
  45. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    959
  46. Common Questions from UIUC school life in terms of CS Program
    1,110
  47. UIUC Immunization Compliance
    1,197
  48. LEE CHANHYUK's songs really resonate with my soul - Time Stop! Vivid LaLa Love, Eve, Endangered Love ...
    1,084
  49. LEE CHANHYUK - Endangered Love (멸종위기사랑)
    1,088
  50. Cupid (OT4/Twin Ver.) - LIVE IN STUDIO | FIFTY FIFTY (피프티피프티)
    862