English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn everything about Python sets; how to create them, add or remove elements from them, and all the operations that can be performed on sets in Python.
Sets are an unordered collection of items. Each element is unique (no duplicates), and must be immutable (cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations, such as union, intersection, and symmetric difference, etc.
By placing all items (elements) within curly braces {} and separating them with commas or using built-in functions to create a set set().
It can have any number of items, and they can have different types (integers, floats, tuples, strings, etc.). However, sets cannot have mutable elements (such aslist, set ordictionary) as its elements.
#Integer set my_set = {1, 2, 3} print(my_set) #Mixed data type set my_set = {1.0, "Hello", (1, 2, 3)} print(my_set)
Try the following example as well.
#No duplicate set # Output: {1, 2, 3, 4} my_set = {1,2,3,4,3,2} print(my_set) #Set cannot contain mutable items #Here [3,4] is a mutable list #If you uncomment line12line, #This will cause an error. #TypeError: unhashable type: 'list' #my_set = {1, 2, [3, 4]) #We can generate a set from a list # Output: {1, 2, 3} my_set = set([1,2,3,2]) print(my_set)
Creating an empty set is a bit special.
Empty parentheses {} create an empty dictionary in Python. To create an empty set with no elements, we use the set() function with no parameters.
#Initialize using {} a = {} #Check the data type of a #Output: <class 'dict'> print(type(a)) #Initialize using set() a = set() #Check the data type of a #Output: <class 'set'> print(type(a))
Sets are mutable. However, since they are unordered, the index has no meaning.
We cannot use indexing or slicing to access or change the elements of a set. Sets do not support it.
We can use the add() method to add a single element, and use the update() method to add multiple elements. The update() method can taketuple,stringor other set as its parameter. In all cases, avoid repetition.
# Initialize my_set my_set = {1,3} print(my_set) #If you uncomment line9line, #You will get an error #TypeError: 'set' object does not support indexing #my_set[0] Add an element # Output: {1, 2, 3} my_set.add(2) print(my_set) Add multiple elements # Output: {1, 2, 3, 4} my_set.update([2,3,4]) print(my_set) Add list and set # Output: {1, 2, 3, 4, 5, 6, 8} my_set.update([4,5], {1,6,8) print(my_set)
When running the program, the output is:
{1, 3} {1, 2, 3} {1, 2, 3, 4} {1, 2, 3, 4, 5, 6, 8}
The discard() and remove() methods can be used to delete specific items from the set.
The only difference between the two is that if discard() is used and the item does not exist in the set, it remains unchanged. However, remove() will raise an error in this case.
The following example will illustrate this.
# Initialize my_set my_set = {1, 3, 4, 5, 6} print(my_set) # Discard an element # Output: {1, 3, 5, 6} my_set.discard(4) print(my_set) Remove an element # Output: {1, 3, 5} my_set.remove(6) print(my_set) # Discard an element # The item is not present in my_set # Output: {1, 3, 5} my_set.discard(2) print(my_set) # Remove an element # The item is not present in my_set # If there is no comment #my_set.remove(2), # An error will be raised. # Output: KeyError: 2 #my_set.remove(2)
Similarly, we can use the pop() method to delete and return an item.
Sets are unordered, so the item popped cannot be determined. This is completely arbitrary.
We can also use the clear() method to delete all items in the set.
# Initialize my_set # Output: Unique element set my_set = set("HelloWorld") print(my_set) # Pop an element # Output: Random element print(my_set.pop()) # Pop an arbitrary element # Output: Random element my_set.pop() print(my_set) # Clear my_set # Output: set() my_set.clear() print(my_set)
Sets can be used to perform mathematical set operations, such as union, intersection, difference, and symmetric difference. We can achieve this through operators or methods.....
Let's consider the following two groups used for the following operations.
>>> A = {1, 2, 3, 4, 5} >>> B = {4, 5, 6, 7, 8}
The union of A and B is a set of all elements from these two sets.
The union is executed using the | operator. It can also be completed using the union() method.
# Initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # Use the | operator # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A | B)
Try the following examples in the Python shell.
# Use the union function >>> A.union(B) {1, 2, 3, 4, 5, 6, 7, 8} # Use the union function on B >>> B.union(A) {1, 2, 3, 4, 5, 6, 7, 8}
>>> BandB'sIntersection is a set of elements that are common to both sets.
Intersection is executed using the & operator. The intersection() method can also achieve the same operation.
# Initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # Use the & operator # Output: {4, 5} print(A & B)
Try the following examples in the Python shell.
# Use the intersection function on A >>> A.intersection(B) {4, 5} # Use the intersection function on B >>> B.intersection(A) {4, 5}
The difference between A and B (A-B) is a set of elements that are only in A but not in B. Similarly, B-A is a set of elements that are in B but not in A.
Difference is using -operator is executed. Using the difference() method can achieve the same operation.
# Initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # Use the difference function on A - operator # Output: {1, 2, 3} print(A - B)
Try the following examples in the Python shell.
# Use the difference function on A >>> A.difference(B) {1, 2, 3} # Use on B-运算符符 The operator ^ executes the symmetric difference. The same operation can be performed using the symmetric_difference() method. - >>> B {8, 6, 7} A # Using the difference function on B {8, 6, 7}
Set Symmetric Difference
The symmetric difference of A and B is a set of elements that are in either A or B, but not in both.
# Initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # Using the ^ operator # Output: {1, 2, 3, 6, 7, 8} print(A ^ B)
Try the following examples in the Python shell.
# Using the symmetric_difference function on A >>> A.symmetric_difference(B) {1, 2, 3, 6, 7, 8} # Using the symmetric_difference function on B >>> B.symmetric_difference(A) {1, 2, 3, 6, 7, 8}
There are many set methods in Python, some of which have been used above. This is a list of all the methods available for the set object.
Method | Description |
---|---|
add() | Add an element to the set |
clear() | Remove all elements from the set |
copy() | Return a copy of the set |
difference() | Return the difference of two or more sets as a new set |
difference_update() | Remove all elements of another set from this set |
discard() | Remove the element from the set if it is a member. (No operation is performed if the element is not in the set) |
intersection() | Return the intersection of two sets as a new set |
intersection_update() | Update the set with the intersection of itself and another |
isdisjoint() | Return True if the intersection of two sets is empty |
issubset() | Return True if another set contains this set |
issuperset() | Return True if this set contains another set |
pop() | Remove and return an arbitrary set element. Raises KeyError if the set is empty |
remove() | Remove an element from the set. If the element is not a member, a KeyError is raised |
symmetric_difference() | Return the symmetric difference of two sets as a new set |
symmetric_difference_update() | Update a set with the symmetric difference of itself and another |
union() | Return the union of elements in the new set |
update() | Update the set with the union of itself and other elements |
We can use the in keyword to test if an item exists in the set.
# Initialize my_set my_set = set("apple") # Check if 'a' exists # Output: True print('a' in my_set) # Check if 'p' exists # Output: False print('p' not in my_set)
Using a for loop, we can iterate over each item in the set.
>>> for letter in set("apple"): ... print(letter) ... a p e l
Built-in functions such as all(), any(), enumerate(), len(), max(), min(), sort(), sum(), and others are commonly used with set to perform different tasks.
Function | Description |
---|---|
all() | Returns True if all elements in the set are true (or the set is empty). |
any() | Returns True if any element in the set is true. If the set is empty, returns False. |
enumerate() | Returns an enumeration object. It contains pairs of all items' indices and values. |
len() | Returns the length of the set (number of items). |
max() | Returns the largest item in the set. |
min() | Returns the smallest item in the set. |
sorted() | Returns a new sorted list of elements from the set (without sorting the set itself). |
sum() | Returns the sum of all elements in the set. |
Frozenset is a new class with set features, but once allocated, its elements cannot be changed. Tuples are immutable lists, while frozensets are immutable sets.
Mutable sets are not hashable and cannot be used as dictionary keys. On the other hand, frozenset is hashable and can be used as a dictionary key.
You can use the functionFrozenset()CreationFrozensets.
This data type supports methods such as copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference(), and union(). Since it is immutable, there are no methods to add or delete elements.
# Initialize A and B A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6])
Try these examples in the Python shell.
>>> A.isdisjoint(B) False >>> A.difference(B) frozenset({1, 2) >>> A | B frozenset({1, 2, 3, 4, 5, 6) >>> A.add(3) ... AttributeError: 'frozenset' object has no attribute 'add'