Python Sets

20 Jun, 2022
In Python, a 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 in the set.
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 set cannot have mutable elements like a list or dictionary, as it is mutable.  
Python3
# Python program to demonstrate# Creation of Set in Python # Creating a Setset1 = set()print("Initial blank Set: ")print(set1) # Creating a Set with# the use of a Stringset1 = set("GeeksForGeeks")print("\nSet with the use of String: ")print(set1) # Creating a Set with# the use of Constructor# (Using object to Store String)String = 'GeeksForGeeks'set1 = set(String)print("\nSet with the use of an Object: " )print(set1) # Creating a Set with# the use of a Listset1 = set(["Geeks", "For", "Geeks"])print("\nSet with the use of List: ")print(set1)
Initial blank Set: 
set()

Set with the use of String: 
{'e', 'r', 'G', 's', 'F', 'k', 'o'}

Set with the use of an Object: 
{'e', 'r', 'G', 's', 'F', 'k', 'o'}

Set with the use of List: 
{'Geeks', 'For'}
A set contains only unique elements but at the time of set creation, multiple duplicate values can also be passed. Order of elements in a set is undefined and is unchangeable. Type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set. 
Python3
# Creating a Set with# a List of Numbers# (Having duplicate values)set1 = set([1, 2, 4, 4, 3, 3, 3, 6, 5])print("\nSet with the use of Numbers: ")print(set1) # Creating a Set with# a mixed type of values# (Having numbers and strings)set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])print("\nSet with the use of Mixed Values")print(set1)
Set with the use of Numbers: 
{1, 2, 3, 4, 5, 6}

Set with the use of Mixed Values
{1, 2, 'For', 4, 6, 'Geeks'}
Python3
# Another Method to create sets in Python3 # Set containing numbersmy_set = {1, 2, 3} print(my_set) # This code is contributed by sarajadhav12052009
{1, 2, 3}
Elements can be added to the Set by using the built-in add() function. Only one element at a time can be added to the set by using add() method, loops are used to add multiple elements at a time with the use of add() method.
Note: Lists cannot be added to a set as elements because Lists are not hashable whereas Tuples can be added because tuples are immutable and hence Hashable. 
Python3
# Python program to demonstrate# Addition of elements in a Set # Creating a Setset1 = set()print("Initial blank Set: ")print(set1) # Adding element and tuple to the Setset1.add(8)set1.add(9)set1.add((6, 7))print("\nSet after Addition of Three elements: ")print(set1) # Adding elements to the Set# using Iteratorfor i in range(1, 6):    set1.add(i)print("\nSet after Addition of elements from 1-5: ")print(set1)
Initial blank Set: 
set()

Set after Addition of Three elements: 
{8, 9, (6, 7)}

Set after Addition of elements from 1-5: 
{1, 2, 3, (6, 7), 4, 5, 8, 9}
For the addition of two or more elements Update() method is used. The update() method accepts lists, strings, tuples as well as other sets as its arguments. In all of these cases, duplicate elements are avoided.
Python3
# Python program to demonstrate# Addition of elements in a Set # Addition of elements to the Set# using Update functionset1 = set([4, 5, (6, 7)])set1.update([10, 11])print("\nSet after Addition of elements using Update: ")print(set1)
Set after Addition of elements using Update: 
{4, 5, (6, 7), 10, 11}
Set items cannot be accessed by referring to an index, since sets are unordered the items has no index. 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.
Python3
# Python program to demonstrate# Accessing of elements in a set # Creating a setset1 = set(["Geeks", "For", "Geeks"])print("\nInitial set")print(set1) # Accessing element using# for loopprint("\nElements of set: ")for i in set1:    print(i, end=" ") # Checking the element# using in keywordprint("Geeks" in set1)
Initial set
{'For', 'Geeks'}

Elements of set: 
For Geeks True
Elements can be removed from the Set by using the built-in remove() function but a KeyError arises if the element doesn’t exist in the set. To remove elements from a set without KeyError, use discard(), if the element doesn’t exist in the set, it remains unchanged.
Python3
# Python program to demonstrate# Deletion of elements in a Set # Creating a Setset1 = set([1, 2, 3, 4, 5, 6,            7, 8, 9, 10, 11, 12])print("Initial Set: ")print(set1) # Removing elements from Set# using Remove() methodset1.remove(5)set1.remove(6)print("\nSet after Removal of two elements: ")print(set1) # Removing elements from Set# using Discard() methodset1.discard(8)set1.discard(9)print("\nSet after Discarding two elements: ")print(set1) # Removing elements from Set# using iterator methodfor i in range(1, 5):    set1.remove(i)print("\nSet after Removing a range of elements: ")print(set1)
Initial Set: 
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Set after Removal of two elements: 
{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}

Set after Discarding two elements: 
{1, 2, 3, 4, 7, 10, 11, 12}

Set after Removing a range of elements: 
{7, 10, 11, 12}
Pop() function can also be used to remove and return an element from the set, but it removes only the last element of the set. 
Note: If the set is unordered then there’s no such way to determine which element is popped by using the pop() function. 
Python3
# Python program to demonstrate# Deletion of elements in a Set # Creating a Setset1 = set([1, 2, 3, 4, 5, 6,            7, 8, 9, 10, 11, 12])print("Initial Set: ")print(set1) # Removing element from the# Set using the pop() methodset1.pop()print("\nSet after popping an element: ")print(set1)
Initial Set: 
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Set after popping an element: 
{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
To remove all the elements from the set, clear() function is used. 
Python3
#Creating a setset1 = set([1,2,3,4,5])print("\n Initial set: ")print(set1)  # Removing all the elements from# Set using clear() methodset1.clear()print("\nSet after clearing all the elements: ")print(set1)
 Initial set: 
{1, 2, 3, 4, 5}

Set after clearing all the elements: 
set()
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. 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.  
Python3
# Python program to demonstrate# working of a FrozenSet # Creating a SetString = ('G', 'e', 'e', 'k', 's', 'F', 'o', 'r') Fset1 = frozenset(String)print("The FrozenSet is: ")print(Fset1) # To print Empty Frozen Set# No parameter is passedprint("\nEmpty FrozenSet: ")print(frozenset())
The FrozenSet is: 
frozenset({'o', 'G', 'e', 's', 'r', 'F', 'k'})

Empty FrozenSet: 
frozenset()
Python3
# Typecasting Objects in Python3 into sets # Typecasting list into setmy_list = [1, 2, 3, 3, 4, 5, 5, 6, 2]my_set = set(my_list)print("my_list as a set: ", my_set) # Typecasting string into setmy_str = "GeeksforGeeks"my_set1 = set(my_str)print("my_str as a set: ", my_set1) # Typecasting dictionary into setmy_dict = {1: "One", 2: "Two", 3: "Three"}my_set2 = set(my_dict)print("my_dict as a set: ", my_set2) # This code is contributed by sarajadhav12052009
my_list as a set:  {1, 2, 3, 4, 5, 6}
my_str as a set:  {'f', 'G', 'r', 'o', 's', 'k', 'e'}
my_dict as a set:  {1, 2, 3}
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
Output of Python programs – Sets
Recent Articles on Python Sets
Multiple Choice Questions – Python
All articles in Python Category
nikhilaggarwal3
Akanksha_Rai
simranarora5sos
anikakapoor
aravindprasadr2021
kalicharan2779
sarajadhav12052009
Python-Built-in-functions
python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python