Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Sets
Next article icon

Sets in Python

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

A Set in Python is used to store a collection of items with the following properties.

  • No duplicate elements. If try to insert the same item again, it overwrites previous one.
  • An unordered collection. When we access all items, they are accessed without any specific order and we cannot access items using indexes as we do in lists.
  • Internally use hashing that makes set efficient for search, insert and delete operations. It gives a major advantage over a list for problems with these operations.
  • Mutable, meaning we can add or remove elements after their creation, the individual elements within the set cannot be changed directly.

Example of Python Sets

Python
s = {10, 50, 20} print(s) print(type(s)) 

Output
{10, 50, 20} <class 'set'> 

Note : There is no specific order for set elements to be printed

Type Casting with Python Set method

The Python set() method is used for type casting.

Python
# typecasting list to set s = set(["a", "b", "c"]) print(s)  # Adding element to the set s.add("d") print(s) 

Output
{'c', 'b', 'a'} {'d', 'c', 'b', 'a'} 

Check unique and  Immutable with Python Set

Python sets cannot have duplicate values. While you cannot modify the individual elements directly, you can still add or remove elements from the set.

Python
# Python program to demonstrate that # a set cannot have duplicate values  # and we cannot change its items  # a set cannot have duplicate values s = {"Geeks", "for", "Geeks"} print(s)  # values of a set cannot be changed s[1] = "Hello" print(s) 

Output:

The first code explains that the set cannot have a duplicate value. Every item in it is a unique value. 

The second code generates an error because we cannot assign or change a value once the set is created. We can only add or delete items in the set.

{'Geeks', 'for'}
TypeError: 'set' object does not support item assignment

Heterogeneous Element with Python Set

Python sets can store heterogeneous elements in it, i.e., a set can store a mixture of string, integer, boolean, etc datatypes.

Python
# Python example demonstrate that a set # can store heterogeneous elements s = {"Geeks", "for", 10, 52.7, True} print(s) 

Output
{True, 'for', 'Geeks', 10, 52.7} 

Python Frozen Sets

Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. It can be done with frozenset() method in Python.

While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. 

If no parameters are passed, it returns an empty frozenset.

Python
# Python program to demonstrate differences # between normal and frozen set  # Same as {"a", "b","c"} s = set(["a", "b","c"])  print("Normal Set") print(s)  # A frozen set fs = frozenset(["e", "f", "g"])  print("\nFrozen Set") print(fs)  # Uncommenting below line would cause error as # we are trying to add element to a frozen set # fs.add("h") 

Output
Normal Set set(['a', 'c', 'b'])  Frozen Set frozenset(['e', 'g', 'f']) 

Internal working of Set

This is based on a data structure known as a hash table.  If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List.

In, Python Sets are implemented using a dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity.

Set Implementation:

HashTable-300x278

Hash Table


Sets with Numerous operations on a single HashTable:

Hasing-Python

Hashing


Methods for Sets

Adding elements to Python Sets

Insertion in the set is done through the set.add() function, where an appropriate record value is created to store in the hash table. Same as checking for an item, i.e., O(1) on average. However, in worst case it can become O(n).

Python
# A Python program to # demonstrate adding elements # in a set  # Creating a Set people = {"Jay", "Idrish", "Archi"}  print("People:", end = " ") print(people)  # This will add Daxit # in the set people.add("Daxit")  # Adding elements to the # set using iterator for i in range(1, 6):     people.add(i)  print("\nSet after adding element:", end = " ") print(people) 

Output
People: {'Idrish', 'Archi', 'Jay'}  Set after adding element: {1, 2, 3, 4, 5, 'Daxit', 'Archi', 'Jay', 'Idrish'} 

Union operation on Python Sets

Two sets can be merged using union() function or | operator. Both Hash Table values are accessed and traversed with merge operation perform on them to combine the elements, at the same time duplicates are removed. The Time Complexity of this is O(len(s1) + len(s2)) where s1 and s2 are two sets whose union needs to be done.

Python
# Python Program to # demonstrate union of # two sets  people = {"Jay", "Idrish", "Archil"} vampires = {"Karan", "Arjun"} dracula = {"Deepanshu", "Raju"}  # Union using union() # function population = people.union(vampires)  print("Union using union() function") print(population)  # Union using "|" # operator population = people|dracula  print("\nUnion using '|' operator") print(population) 

Output
Union using union() function {'Idrish', 'Arjun', 'Jay', 'Karan', 'Archil'}  Union using '|' operator {'Idrish', 'Deepanshu', 'Raju', 'Jay', 'Archil'} 

Intersection operation on Python Sets

This can be done through intersection() or & operator. Common Elements are selected. They are similar to iteration over the Hash lists and combining the same values on both the Table. Time Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union needs to be done.

Python
# Python program to # demonstrate intersection # of two sets  set1 = set() set2 = set()  for i in range(5):     set1.add(i)  for i in range(3,9):     set2.add(i)  # Intersection using # intersection() function set3 = set1.intersection(set2)  print("Intersection using intersection() function") print(set3)  # Intersection using # "&" operator set3 = set1 & set2  print("\nIntersection using '&' operator") print(set3) 

Output
Intersection using intersection() function {3, 4}  Intersection using '&' operator {3, 4} 

Finding Differences of Sets in Python

To find differences between sets. Similar to finding differences in the linked list. This is done through difference() or – operator. Time complexity of finding difference s1 – s2 is O(len(s1))

Python
# Python program to # demonstrate difference # of two sets  set1 = set() set2 = set()  for i in range(5):     set1.add(i)  for i in range(3,9):     set2.add(i)  # Difference of two sets # using difference() function set3 = set1.difference(set2)  print(" Difference of two sets using difference() function") print(set3)  # Difference of two sets # using '-' operator set3 = set1 - set2  print("\nDifference of two sets using '-' operator") print(set3) 

Output
 Difference of two sets using difference() function {0, 1, 2}  Difference of two sets using '-' operator {0, 1, 2} 

Clearing Python Sets

Set Clear() method empties the whole set inplace.

Python
# Python program to # demonstrate clearing # of set  set1 = {1,2,3,4,5,6}  print("Initial set") print(set1)  # This method will remove # all the elements of the set set1.clear()  print("\nSet after using clear() function") print(set1) 

Output
Initial set {1, 2, 3, 4, 5, 6}  Set after using clear() function set() 

However, there are two major pitfalls in Python sets: 

  1. The set doesn’t maintain elements in any particular order.
  2. Only instances of immutable types can be added to a Python set.

Time complexity of Sets

OperationAverage caseWorst Casenotes
x in sO(1)O(n) 
Union s|tO(len(s)+len(t))  
Intersection s&tO(min(len(s), len(t))O(len(s) * len(t))replace “min” with “max” if t is not a set
Multiple intersection s1&s2&..&sn (n-1)*O(l) where l is max(len(s1),..,len(sn)) 
Difference s-tO(len(s))  

Operators for Sets

Sets and frozen sets support the following operators:

OperatorsNotes
key in scontainment check
key not in snon-containment check
s1 == s2s1 is equivalent to s2
s1 != s2s1 is not equivalent to s2
s1 <= s2s1 is subset of s2
s1 < s2s1 is proper subset of s2
s1 >= s2s1 is superset of s2
s1 > s2s1 is proper superset of s2
s1 | s2the union of s1 and s2
s1 & s2the intersection of s1 and s2
s1 – s2the set of elements in s1 but not s2
s1 ˆ s2the set of elements in precisely one of s1 or s2

Problems based on Set

  • Distinct Elements in an Array
  • Union of Two Arrays
  • Intersection of Two Arrays
  • Distinct Elements in an Array
  • Union of Two Arrays
  • Intersection of Two Arrays
  • Repeating Elements
  • Check if an Array is Subset of other
  • Check Pair with Target Sum
  • Check for Disjoint Arrays or Sets
  • Duplicate within K Distance
  • Longest Consecutive Sequence
  • Check for Disjoint Arrays or Sets
  • Duplicate within K Distance in an Array
  • 2 Sum – Check for Pair with target sum
  • Longest Consecutive Sequence
  • Only Repeating Element From 1 To n-1

Recent articles on Python Set.



Next Article
Python Sets
author
kartik
Improve
Article Tags :
  • Python
  • python-set
Practice Tags :
  • python
  • python-set

Similar Reads

  • Sets in Python
    A Set in Python is used to store a collection of items with the following properties. No duplicate elements. If try to insert the same item again, it overwrites previous one.An unordered collection. When we access all items, they are accessed without any specific order and we cannot access items usi
    9 min read
  • Python Sets
    Python set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change. Creating a Set in PythonIn Python, the most basic and efficient method for creatin
    11 min read
  • Internal working of Set in Python
    Sets and their working Set in Python can be defined as the collection of items. In Python, these are basically used to include membership testing and eliminating duplicate entries. The data structure used in this is Hashing, a popular technique to perform insertion, deletion and traversal in O(1) on
    3 min read
  • Find the length of a set in Python
    We are given a set and our task is to find its length. For example, if we have a = {1, 2, 3, 4, 5}, the length of the set should be 5. Using len()len() function in Python returns the number of elements in a set. It provides total count of unique items present in set. [GFGTABS] Python a = {1, 2, 3, 4
    2 min read
  • Checking Element Existence in a Python Set
    We are given a set and our task is to check if a specific element exists in the given set. For example, if we have s = {21, 24, 67, -31, 50, 11} and we check for the element 21, which is present in the set then the output should be True. Let's explore different ways to perform this check efficiently
    2 min read
  • Python - Append Multiple elements in set
    In Python, sets are an unordered and mutable collection of data type what does not contains any duplicate elements. In this article, we will learn how to append multiple elements in the set at once. Example: Input: test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 10]Output: {1, 2, 4, 5, 6, 7, 9, 10}Expla
    4 min read
  • Remove items from Set - Python
    We are given a set and our task is to remove specific items from the given set. For example, if we have a = {1, 2, 3, 4, 5} and need to remove 3, the resultant set should be {1, 2, 4, 5}. Using remove()remove() method in Python is used to remove a specific item from a set. If the item is not present
    2 min read
  • Python - Remove multiple elements from Set
    Given a set, the task is to write a Python program remove multiple elements from set. Example: Input : test_set = {6, 4, 2, 7, 9}, rem_ele = [2, 4, 8] Output : {9, 6, 7} Explanation : 2, 4 are removed from set. Input : test_set = {6, 4, 2, 7, 9}, rem_ele = [4, 8] Output : {2, 9, 6, 7} Explanation :
    4 min read
  • Python program to remove last element from set
    Given a set, the task is to write a Python program to delete the last element from the set. Example: Input: {1,2,3,4}Remove 4Output: {1,2,3} Input: {"Geeks","For"}Remove GeeksOutput: {"For"}Explanation: The idea is to remove the last element from the set 4 in the first case and "Geeks" in the second
    2 min read
  • Python Program to Find Duplicate sets in list of sets
    Given a list of sets, the task is to write a Python program to find duplicate sets. Input : test_list = [{4, 5, 6, 1}, {6, 4, 1, 5}, {1, 3, 4, 3}, {1, 4, 3}, {7, 8, 9}]Output : [frozenset({1, 4, 5, 6}), frozenset({1, 3, 4})]Explanation : {1, 4, 5, 6} is similar to {6, 4, 1, 5} hence part of result.
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences