Sets in Python

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Set in Python programming is an unordered collection data type that is iterable, mutable and has no duplicate elements. 

Set are represented by { } (values enclosed in curly braces)

The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table. Since sets are unordered, we cannot access items using indexes as we do in lists.

Example of Python Sets

Python
var = {"Geeks", "for", "Geeks"}
type(var)

Output:

set

Time Complexity: O(1)
Auxiliary Space: O(1)

Type Casting with Python Set method

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

Python
# typecasting list to set
myset = set(["a", "b", "c"])
print(myset)

# Adding element to the set
myset.add("d")
print(myset)

Output:

Python set is an unordered datatype, which means we cannot know in which order the elements of the set are stored.

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

Time Complexity: O(n)
Auxiliary Space: O(n)

Check unique and  Immutable with Python Set

Python sets cannot have a duplicate value and once it is created we cannot change its value.

Python
# Python program to demonstrate that
# a set cannot have duplicate values 
# and we cannot change its items

# a set cannot have duplicate values
myset = {"Geeks", "for", "Geeks"}
print(myset)

# values of a set cannot be changed
myset[1] = "Hello"
print(myset)

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
myset = {"Geeks", "for", 10, 52.7, True}
print(myset)

Output:

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

Time Complexity: O(n)
Auxiliary Space: O(n)

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"}
normal_set = set(["a", "b","c"])

print("Normal Set")
print(normal_set)

# A frozen set
frozen_set = frozenset(["e", "f", "g"])

print("\nFrozen Set")
print(frozen_set)

# Uncommenting below line would cause error as
# we are trying to add element to a frozen set
# frozen_set.add("h")

Output:

Normal Set
{'a', 'c', 'b'}

Frozen Set
{'e', 'g', 'f'}

Time Complexity: O(n)
Auxiliary Space: O(n)

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:

Sets in Python - Internal Working

 

Sets with Numerous operations on a single HashTable:

Sets in Python - Hash Table

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, 'Idrish', 'Archi', 'Jay', 'Daxit'}

Time Complexity: O(n)
Auxiliary Space: O(n)

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
{'Karan', 'Idrish', 'Jay', 'Arjun', 'Archil'}

Union using '|' operator
{'Deepanshu', 'Idrish', 'Jay', 'Raju', 'Archil'}

Time Complexity: O(n)
Auxiliary Space: O(n)

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}

Time Complexity: O(n)
Auxiliary Space: O(n)

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}

Time Complexity: O(n)
Auxiliary Space: O(n)

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()

Time Complexity: O(n)
Auxiliary Space: O(n)

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

Recent articles on Python Set.

Sets in Python – FAQs

What are sets in Python?

Sets in Python are unordered collections of unique elements. They are defined using curly braces {} or the set() function and are useful for storing distinct items and performing mathematical set operations like union, intersection, and difference.

# Creating a set
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}

# Using the set() function
another_set = set([1, 2, 3, 4])
print(another_set) # Output: {1, 2, 3, 4}

How do you calculate sets in Python?

Sets in Python support various operations for calculating unions, intersections, differences, and symmetric differences.

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union
print(set1 | set2) # Output: {1, 2, 3, 4, 5}

# Intersection
print(set1 & set2) # Output: {3}

# Difference
print(set1 - set2) # Output: {1, 2}

# Symmetric Difference
print(set1 ^ set2) # Output: {1, 2, 4, 5}

What is set and tuple in Python?

  • Set: An unordered collection of unique elements. Defined with curly braces {} or set(). Elements cannot be accessed by index.
  • Tuple: An ordered collection of elements. Defined with parentheses () or tuple(). Elements can be accessed by index. Tuples are immutable.

Do sets exist in Python?

Yes, sets exist in Python and are part of the built-in data types provided by the language. They are commonly used for membership tests, removing duplicates from a sequence, and performing set operations.

my_set = {1, 2, 3}
print(2 in my_set) # Output: True

How to input set in Python?

To input a set in Python, you can use the input() function to get user input and then convert it into a set. For example, you can read a string of numbers separated by spaces and convert them to a set of integers.

# Input a set from user
input_str = input("Enter elements separated by space: ")
input_list = input_str.split() # Split the input string into a list
input_set = set(map(int, input_list)) # Convert list to set of integers

print(input_set) # Output: Set of input elements

This code snippet allows the user to input a set of numbers separated by spaces, which are then converted into a set of integers.



Similar Reads

Output of Python Programs | Set 24 (Sets)
Prerequisite: Python-Sets 1. What is the output of the code shown below? sets = {1, 2, 3, 4, 4} print(sets) Options: {1, 2, 3} {1, 2, 3, 4} {1, 2, 3, 4, 4} Error Output: 2. {1, 2, 3, 4} Explanation : Duplicate values are not allowed in sets. Hence, the output of the code shown above will be a set containing the duplicate value only once. Hence outp
2 min read
Python Set | Pairs of complete strings in two sets
Two strings are said to be complete if on concatenation, they contain all the 26 English alphabets. For example, “abcdefghi” and “jklmnopqrstuvwxyz” are complete as they together have all characters from ‘a’ to ‘z’. We are given two sets of sizes n and m respectively and we need to find the number of pairs that are complete on concatenating each st
2 min read
Python | sympy.sets.open() method
With the help of sympy.sets.open() method, we can make a set of values by setting interval values like right open or left open that means a set has right open bracket and left open brackets by using sympy.sets.open() method. Syntax : sympy.sets.open(val1, val2) Return : Return set of values with right and left open set. Example #1 : In this example
1 min read
Python | sympy.sets.Ropen() method
With the help of sympy.sets.Ropen() method, we can make a set of values by setting interval values like right open that means a set has right open bracket and left close one by using sympy.sets.Ropen() method. Syntax : sympy.sets.Ropen(val1, val2) Return : Return set of values with right open set. Example #1 : In this example we can see that by usi
1 min read
Python | sympy.sets.Lopen() method
With the help of sympy.sets.Lopen() method, we can make a set of values by setting interval values like left open that means a set has left open bracket and right close one by using sympy.sets.Lopen() method. Syntax : sympy.sets.Lopen(val1, val2) Return : Return set of values with left open set. Example #1 : In this example we can see that by using
1 min read
Python Tokens and Character Sets
Python is a general-purpose, high-level programming language. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code, and these codes are known as scripts. These scripts contain character sets, tokens, and identifiers. In this article, we will learn about these charac
6 min read
Python | remove() and discard() in Sets
In this article, we will see how to remove an element in a set, using the discard() and remove() method. We will also learn the difference between the two methods, although they produce the same results. Example Input: set = ([10, 20, 26, 41, 54, 20]) Output: {41, 10, 26, 54} Input: set = (["ram", "aakash", "kaushik", "anand", "prashant"]) Output:
3 min read
Python Sets
Python Set is an unordered collection of data types that is iterable, mutable, and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained i
15 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python Debugger – Python pdb
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
5 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Top 10 Python Built-In Decorators That Optimize Python Code Significantly
Python is a widely used high-level, general-purpose programming language. The language offers many benefits to developers, making it a popular choice for a wide range of applications including web development, backend development, machine learning applications, and all cutting-edge software technology, and is preferred for both beginners as well as
12 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
GeeksforGeeks Python Foundation Course - Learn Python in Hindi!
Python - it is not just an ordinary programming language but the doorway or basic prerequisite for getting into numerous tech domains including web development, machine learning, data science, and several others. Though there's no doubt that the alternatives of Python in each of these respective areas are available - but the dominance and popularit
5 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python Image Editor Using Python
You can create a simple image editor using Python by using libraries like Pillow(PIL) which will provide a wide range of image-processing capabilities. In this article, we will learn How to create a simple image editor that can perform various operations like opening an image, resizing it, blurring the image, flipping and rotating the image, and so
13 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Article Tags :
Practice Tags :