Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Internal working of Set in Python
Next article icon

Python Sets

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

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 Python

In Python, the most basic and efficient method for creating a set is using curly braces.

Example:

Python
set1 = {1, 2, 3, 4} print(set1) 

Output
{1, 2, 3, 4} 

Using the set() function

Python Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by a 'comma'.

Note: A Python set cannot have mutable elements like a list or dictionary, as it is immutable. 

Example:

Python
set1 = set() print(set1)  set1 = set("GeeksForGeeks") print(set1)  # Creating a Set with the use of a List set1 = set(["Geeks", "For", "Geeks"]) print(set1)  # Creating a Set with the use of a tuple tup = ("Geeks", "for", "Geeks") print(set(tup))  # Creating a Set with the use of a dictionary d = {"Geeks": 1, "for": 2, "Geeks": 3} print(set(d)) 

Output
set() {'e', 'r', 'o', 'k', 'G', 's', 'F'} {'For', 'Geeks'} {'for', 'Geeks'} {'for', 'Geeks'} 

Unordered, Unindexed and Mutability

In set, the order of elements is not guaranteed to be the same as the order in which they were added. The output could vary each time we run the program. Also the duplicate items entered are removed by itself.

Sets do not support indexing. Trying to access an element by index (set[0]) raises a TypeError.

We can add elements to the set using add(). We can remove elements from the set using remove(). The set changes after these operations, demonstrating its mutability. However, we cannot changes its items directly.

Example:

Python
set1 = {3, 1, 4, 1, 5, 9, 2}  print(set1)  # Output may vary: {1, 2, 3, 4, 5, 9}  # Unindexed: Accessing elements by index is not possible # This will raise a TypeError try:     print(set1[0]) except TypeError as e:     print(e) 

Output
{1, 2, 3, 4, 5, 9} 'set' object is not subscriptable 

Adding Elements to a Set in Python

We can add items to a set using add() method and update() method. add() method can be used to add only a single item. To add multiple items we use update() method.

Example:

Python
# Creating a set set1 = {1, 2, 3}  # Add one item set1.add(4)  # Add multiple items set1.update([5, 6])  print(set1) 

Output
{1, 2, 3, 4, 5, 6} 

Accessing a Set in Python

We can loop through a set to access set items as set is unindexed and do not support accessing elements by indexing. Also we can use in keyword which is membership operator to check if an item exists in a set.

Example:

Python
set1 = set(["Geeks", "For", "Geeks."])  # Accessing element using For loop for i in set1:     print(i, end=" ")  # Checking the element# using in keyword print("Geeks" in set1) 

Output
Geeks For Geeks. True 

Explanation:

  • This loop will print each item in the set. Since sets are unordered, the order of items printed is not guaranteed.
  • This code checks if the number 4 is in set1 and prints a corresponding message.

Removing Elements from the Set in Python

We can remove an element from a set in Python using several methods: remove(), discard() and pop(). Each method works slightly differently :

  • Using remove() Method or discard() Method
  • Using pop() Method
  • Using clear() Method

Using remove() Method or discard() Method

remove() method removes a specified element from the set. If the element is not present in the set, it raises a KeyError. discard() method also removes a specified element from the set. Unlike remove(), if the element is not found, it does not raise an error.

Python
# Using Remove Method set1 = {1, 2, 3, 4, 5} set1.remove(3) print(set1)    # Attempting to remove an element that does not exist try:     set1.remove(10) except KeyError as e:     print("Error:", e)    # Using discard() Method set1.discard(4) print(set1)    # Attempting to discard an element that does not exist set1.discard(10)  # No error raised print(set1)   

Output
{1, 2, 4, 5} Error: 10 {1, 2, 5} {1, 2, 5} 

Using pop() Method

pop() method removes and returns an arbitrary element from the set. This means we don't know which element will be removed. If the set is empty, it raises a KeyError.

Note: If the set is unordered then there's no such way to determine which element is popped by using the pop() function. 

Python
set1 = {1, 2, 3, 4, 5} val = set1.pop() print(val) print(set1)  # Using pop on an empty set set1.clear()  # Clear the set to make it empty try:     set1.pop() except KeyError as e:     print("Error:", e)   

Output
1 {2, 3, 4, 5} Error: 'pop from an empty set' 

Using clear() Method

clear() method removes all elements from the set, leaving it empty.

Python
set1 = {1, 2, 3, 4, 5} set1.clear() print(set1)   

Output
set() 

Frozen Sets in Python

A frozenset in Python is a built-in data type that is similar to a set but with one key difference that is immutability. This means that once a frozenset is created, we cannot modify its elements that is we cannot add, remove or change any items in it. Like regular sets, a frozenset cannot contain duplicate elements.

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

Python
# Creating a frozenset from a list fset = frozenset([1, 2, 3, 4, 5]) print(fset)    # Creating a frozenset from a set set1 = {3, 1, 4, 1, 5} fset = frozenset(set1) print(fset)   

Output
frozenset({1, 2, 3, 4, 5}) frozenset({1, 3, 4, 5}) 

Typecasting Objects into Sets

Typecasting objects into sets in Python refers to converting various data types into a set. Python provides the set() constructor to perform this typecasting, allowing us to convert lists, tuples and strings into sets.

Python
# Typecasting list into set li = [1, 2, 3, 3, 4, 5, 5, 6, 2] set1 = set(li) print(set1)  # Typecasting string into set s = "GeeksforGeeks" set1 = set(s) print(set1)  # Typecasting dictionary into set d = {1: "One", 2: "Two", 3: "Three"} set1 = set(d) print(set1) 

Output
{1, 2, 3, 4, 5, 6} {'f', 'G', 's', 'k', 'r', 'e', 'o'} {1, 2, 3} 

Advantages of Set in Python

  • Unique Elements: Sets can only contain unique elements, so they can be useful for removing duplicates from a collection of data.
  • Fast Membership Testing: Sets are optimized for fast membership testing, so they can be useful for determining whether a value is in a collection or not.
  • Mathematical Set Operations: Sets support mathematical set operations like union, intersection and difference, which can be useful for working with sets of data.
  • Mutable: Sets are mutable, which means that you can add or remove elements from a set after it has been created.

Disadvantages of Sets in Python

  • Unordered: Sets are unordered, which means that you cannot rely on the order of the data in the set. This can make it difficult to access or process data in a specific order.
  • Limited Functionality: Sets have limited functionality compared to lists, as they do not support methods like append() or pop(). This can make it more difficult to modify or manipulate data stored in a set.
  • Memory Usage: Sets can consume more memory than lists, especially for small datasets. This is because each element in a set requires additional memory to store a hash value.
  • Less Commonly Used: Sets are less commonly used than lists and dictionaries in Python, which means that there may be fewer resources or libraries available for working with them. This can make it more difficult to find solutions to problems or to get help with debugging.

Overall, sets can be a useful data structure in Python, especially for removing duplicates or for fast membership testing. However, their lack of ordering and limited functionality can also make them less versatile than lists or dictionaries, so it is important to carefully consider the advantages and disadvantages of using sets when deciding which data structure to use in your Python program.

Set Methods in Python

FunctionDescription
add()Adds an element to a set
remove()Removes an element from a set. If the element is not present in the set, raise a KeyError
clear()Removes all elements form a set
copy()Returns a shallow copy of a set
pop()Removes and returns an arbitrary set element. Raise KeyError if the set is empty
update()Updates a set with the union of itself and others
union()Returns the union of sets in a new set
difference()Returns the difference of two or more sets as a new set
difference_update()Removes all elements of another set from this set
discard()Removes an element from set if it is a member. (Do nothing if the element is not in set)
intersection()Returns the intersection of two sets as a new set
intersection_update()Updates the set with the intersection of itself and another
isdisjoint()Returns True if two sets have a null intersection
issubset()Returns True if another set contains this set
issuperset()Returns True if this set contains another set
symmetric_difference()Returns the symmetric difference of two sets as a new set
symmetric_difference_update()Updates a set with the symmetric difference of itself and another

Recent Articles on Python Sets

Set Programs

  • Program to accept the strings which contains all vowels
  • Python program to find common elements in three lists using sets
  • Find missing and additional values in two lists
  • Pairs of complete strings in two sets
  • Check whether a given string is Heterogram or not
  • Maximum and Minimum in a Set
  • Remove items from Set
  • Python Set difference to find lost element from a duplicated array
  • Minimum number of subsets with distinct elements using Counter
  • Check if two lists have at-least one element common
  • Program to count number of vowels using sets in given string
  • Difference between two lists
  • Python set to check if string is panagram
  • Python set operations (union, intersection, difference and symmetric difference)
  • Concatenated string with uncommon characters in Python
  • Python dictionary, set and counter to check if frequencies can become same
  • Using Set() in Python Pangram Checking
  • Set update() in Python to do union of n arrays

Useful Links

  • Output of Python programs – Sets
  • Recent Articles on Python Sets
  • Multiple Choice Questions – Python
  • All articles in Python Category

Next Article
Internal working of Set in Python

A

abhishek1
Improve
Article Tags :
  • Misc
  • Python
  • python-set
  • Python-Built-in-functions
Practice Tags :
  • Misc
  • 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 usin
    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 creating
    10 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.Pythona = {1, 2, 3, 4, 5} # Return
    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