Python set is anunordered collectionof multiple items having different datatypes. In Python, sets aremutable,unindexedand 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:
Pythonset1={1,2,3,4}print(set1)
Using the set() function
Python Sets can be created by using the built-inset() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by a 'comma'.
Note:A Python set cannot contain mutable types such as lists or dictionaries, because they are unhashable.
Example:
Pythonset1=set()print(set1)set1=set("GeeksForGeeks")print(set1)# Creating a Set with the use of a Listset1=set(["Geeks","For","Geeks"])print(set1)# Creating a Set with the use of a tupletup=("Geeks","for","Geeks")print(set(tup))# Creating a Set with the use of a dictionaryd={"Geeks":1,"for":2,"Geeks":3}print(set(d))
Outputset(){'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 aTypeError.
We can add elements to the set usingadd(). We can remove elements from the set usingremove(). The set changes after these operations, demonstrating its mutability. However, we cannot changes its items directly.
Example:
Pythonset1={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 TypeErrortry:print(set1[0])exceptTypeErrorase: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 usingadd() method andupdate() method. add() method can be used to add only a single item. To add multiple items we use update() method.
Example:
Python# Creating a setset1={1,2,3}# Add one itemset1.add(4)# Add multiple itemsset1.update([5,6])print(set1)
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 usein keyword which is membership operator to check if an item exists in a set.
Example:
Pythonset1=set(["Geeks","For","Geeks."])# Accessing element using For loopforiinset1:print(i,end=" ")# Checking the element# using in keywordprint("Geeks"inset1)
OutputGeeks 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
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 Methodset1={1,2,3,4,5}set1.remove(3)print(set1)# Attempting to remove an element that does not existtry:set1.remove(10)exceptKeyErrorase:print("Error:",e)# Using discard() Methodset1.discard(4)print(set1)# Attempting to discard an element that does not existset1.discard(10)# No error raisedprint(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.
Pythonset1={1,2,3,4,5}val=set1.pop()print(val)print(set1)# Using pop on an empty setset1.clear()# Clear the set to make it emptytry:set1.pop()exceptKeyErrorase:print("Error:",e)
Output1{2, 3, 4, 5}Error: 'pop from an empty set'
Using clear() Method
clear() method removes all elements from the set, leaving it empty.
Pythonset1={1,2,3,4,5}set1.clear()print(set1)
Frozen Sets in Python
Afrozensetin 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 listfset=frozenset([1,2,3,4,5])print(fset)# Creating a frozenset from a setset1={3,1,4,1,5}fset=frozenset(set1)print(fset)
Outputfrozenset({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 setli=[1,2,3,3,4,5,5,6,2]set1=set(li)print(set1)# Typecasting string into sets="GeeksforGeeks"set1=set(s)print(set1)# Typecasting dictionary into setd={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
Function | Description |
---|
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 |
Set Programs
Useful Links