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:
Find the length of a set in Python
Next article icon

Internal working of Set in Python

Last Updated : 10 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A Set in Python can be defined as a collection of unique items. It is an unordered collection that does not allow duplicate entries. Sets are primarily used for membership testing and eliminating duplicates from a sequence. The underlying data structure used in sets is Hashing, which allows insertion, deletion, and traversal operations in O(1) on average. Operations on Hash Tables are similar to those on Linked Lists, and sets in Python are unordered collections with duplicate elements removed.

Basic Methods on Sets

1. Creating a Set

In Python, sets are created using the set() function. This creates an empty set. It’s important to note that an empty set cannot be created using {}, as it will create an empty dictionary instead.

x = set() # Creates an empty set

2. Checking if an Item is in a Set

To check if an item exists in a set, you can use the in keyword. The average time complexity for this operation is O(1), but in the worst case, it can become O(n).

‘pear’ in fruit # Fast membership testing.

3. Adding Elements

Elements are added to a set using the add() function. The insertion in a set is efficient, with an average time complexity of O(1). However, in the worst case, it can be O(n).

A.add(‘h’) # Adds ‘h’ to the set

4. Union

The union of two sets can be performed using the union() method or the | operator. The union operation combines elements from both sets while removing duplicates. The time complexity is O(len(s1) + len(s2)), where s1 and s2 are the two sets being merged.

A | B # Union of sets A and B

5. Intersection

To find the common elements between two sets, you can use the intersection() method or the & operator. The time complexity for this operation is O(min(len(s1), len(s2))), where s1 and s2 are the sets being compared.

A & B # Intersection of sets A and B

6. Difference

The difference between two sets can be found using the difference() method or the – operator. The time complexity for this operation is O(len(s1)), where s1 is the set from which elements are being subtracted.

A – B # Elements in A but not in B

7. Symmetric Difference

The symmetric difference between two sets is the set of elements that are in either of the sets but not in both. This operation can be done using the symmetric_difference() method or the ^ operator. The time complexity is O(len(s1)).

A ^ B # Symmetric difference between sets A and B

8. Symmetric Difference Update

The symmetric_difference_update() method modifies the set in place to contain the symmetric difference of the two sets. The time complexity for this operation is O(len(s2)).

A.symmetric_difference_update(B)

9. Clear

The clear() method removes all elements from the set, effectively making it an empty set. This operation has a time complexity of O(n).

A.clear() # Clears all elements from set A

Set Implementation

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 dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity. Set Implementation:

HashTable-300x278

Set Implementation

Sets with Numerous operations on a single HashTable:

Hasing-Python

Numerous operations on a single HashTable

Examples of Set Operations

Here are some examples demonstrating how sets work in Python:

Creating Sets:

Python
x = set() print(x)  B = set('hello') print(B) 

Output
set() {'h', 'o', 'l', 'e'} 

Adding Elements:

Python
A = set('abcdefg') print(A)  A.add('h') print(A) 

Output
{'a', 'g', 'b', 'f', 'c', 'e', 'd'} {'a', 'g', 'h', 'b', 'f', 'c', 'e', 'd'} 

Membership Testing:

Python
fruit = {'orange', 'banana', 'pear', 'apple'} print('pear' in fruit) print('mango' in fruit) 

Output
True False 

Set Operations:

Python
A = set('abcdefg') B = set('hello')  print(A == B) print(A != B) print(A <= B) print(A < B) print(A > B) print(A | B) print(A & B) print(A - B) print(A ^ B) 

Output
False True False False False {'g', 'c', 'h', 'e', 'o', 'd', 'l', 'b', 'a', 'f'} {'e'} {'a', 'g', 'd', 'b', 'c', 'f'} {'g', 'c', 'o', 'l', 'd', 'h', 'a', 'f', 'b'} 

Set Comprehension:

Python
A = set('abcdefg')  a = {x for x in A if x not in 'abc'} print(a) 

Output
{'g', 'f', 'd', 'e'} 

Related Articles:

  • Sets in Python
  • Union
  • Intersection
  • Difference
  • Symmetric Difference
  • Symmetric Difference Update


Next Article
Find the length of a set in Python

K

kartikeya shukla 1
Improve
Article Tags :
  • Python
Practice Tags :
  • python

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
    A Set in Python can be defined as a collection of unique items. It is an unordered collection that does not allow duplicate entries. Sets are primarily used for membership testing and eliminating duplicates from a sequence. The underlying data structure used in sets is Hashing, which allows insertio
    4 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