1. Characteristics of Set in Python
The set data structure in Python helps store many elements. However, the elements in the Set have no order (unordered), cannot be changed (unchangeable), and are not indexed (unindexed). In particular, a Set cannot contain two identical elements.
To create a Set in Python, we put the elements of the Set in curly brackets. Example:
# Set include string
my_set = {'goc', 'it', 'hoc', 'com'}
print("Set include string:", my_set)
# Set include integer
my_set = {1, 0, -1, 9, 5}
print("Set include integer:", my_set)
# Set include string, integer and boolean
my_set = {'gochocit', 7, False, 2, True}
print("Set include string, integer and boolean:", my_set)
# Set include float, tuple
my_set = {7.5, ('goc', 'hoc', 'it')}
print("Set include float, list, tuple:", my_set)
Result
Set include string: {'hoc', 'com', 'it', 'goc'}
Set include integer: {0, 1, 5, 9, -1}
Set include string, integer and boolean: {False, True, 2, 'gochocit', 7}
Set include float, list, tuple: {('goc', 'hoc', 'it'), 7.5}
Elements in the Set can have different data types such as string, float, integer, tuple, etc. But the elements of the Set cannot be a list, set, or dictionary.
In a Set, you cannot have two identical elements. If you try to declare two identical elements in a Set, it will only accept one of them.
# Set not allowed duplicate items
my_set = {'gochocit', 'com', 'hoc', 'com'}
print("Set not allowed duplicate items:", my_set)
Result
Set not allowed duplicate items: {'hoc', 'com', 'gochocit'}
Using the set() function to create a Set
# Create set from list
my_set = set(['gochocit', 'hoc', 'com'])
print(my_set)
# Create set from tuple
my_set = set(('hello', 1, -7.5))
print(my_set)
# Create empty set
my_set = set()
print("Create empty set:", type(my_set))
# Cannot create empty set with {}
my_set = {}
print("Cannot create empty set with {}:", type(my_set))
Result
{'gochocit', 'com', 'hoc'}
{1, -7.5, 'hello'}
Create empty set: <class 'set'>
Cannot create empty set with {}: <class 'dict'>
Size of Set in Python
Use the len()
function to return the number of elements in the Set.
# Sise of set
my_set = set(['gochocit', 'hoc', 'com'])
print("Size of set:", len(my_set))
Result
Size of set: 3
2. Accessing elements of Set data structure in Python
The elements in the Set have no order and are not indexed. Therefore, it is not possible to use the index to access the elements of the Set. We only have a way to use the for loop to iterate through the elements in the Set.
my_set = {'gochocit', True, 'hoc', 5, 'com'}
for x in my_set:
print(x, end=' ')
Result
True gochocit 5 com hoc
Check if an element is in Set or not.
my_set = {'gochocit', True, 'hoc', 5, 'com'}
# True
print("gochocit" in my_set)
# False
print("hello" in my_set)
Result
True
False
3. Add and remove elements in the Set data structure in Python
The elements in the Set data structure in Python cannot change but we can add or remove elements in the Set.
3.1. Add an element to Set
Using the add() function
The add()
function helps add an element to the Set.
my_set = {'gochocit', True, 5, 'com'}
# Add an item to my_set
my_set.add("hello")
print("Add an item to my_set:", my_set)
# Add an existed item to my_set
# my_set ignored this item
my_set.add("com")
print("Add an existed item to my_set:", my_set)
Result
Add an item to my_set: {True, 'gochocit', 5, 'hello', 'com'}
Add an existed item to my_set: {True, 'gochocit', 5, 'hello', 'com'}
Using the update() function
The update()
function helps add the elements of one Set to another Set. The update()
function can also help add the elements of an iterable object such as a list, tuple, dictionary, etc. to a Set.
my_set = {'gochocit', True, 5, 'com'}
my_set1 = {2, 3, 9}
# Add set to set
my_set.update(my_set1)
print("Update my_set:", my_set)
# Add list to set
my_list = ["hello", "John"]
my_set.update(my_list)
print("Update my_set:", my_set)
Result
Update my_set: {True, 2, 3, 5, 'com', 'gochocit', 9}
Update my_set: {True, 2, 3, 5, 'com', 9, 'hello', 'gochocit', 'John'}
3.2. Remove an element of Set
Using the remove() function
It has the function of removing an element in the Set. If the element to be deleted does not exist in the Set, it will cause an error.
my_set = {'gochocit', True, 5, 'com'}
# Remove an item from my_set
my_set.remove("com")
# Output: {True, 'gochocit', 5}
print("Remove an item from my_set", my_set)
# Remove an item which not existed from my_set
# KeyError: 'hello'
my_set.remove("hello")
Using the discard() function
It has the function of removing an element in the Set. If the element to be deleted does not exist in the Set, it will not cause an error.
my_set = {'gochocit', True, 5, 'com'}
# Discard an item from my_set
my_set.discard("com")
# Output: {'gochocit', 5, True}
print("Remove an item from my_set", my_set)
# Discard an item which not existed from my_set
my_set.discard("hello")
Using the pop() function
We can use the pop()
function to delete an item in the Set. In this case, the method will delete the last element of the Set. However, the Set has no order, so we don’t know which element is the last element of the Set to be deleted.
my_set = {'gochocit', True, 5, 'com'}
# Item is removed by pop()
x = my_set.pop()
print("Item is removed by pop():", x)
print("my_set after pop():", my_set)
Result of 1st run
Item is removed by pop(): True
my_set after pop(): {'gochocit', 5, 'com'}
The output of 2nd run
Item is removed by pop(): gochocit
my_set after pop(): {5, 'com', True}
Result of 3rd run
Item is removed by pop(): com
my_set after pop(): {'gochocit', 5, True}
Using the clear() function
It has the function of deleting all elements in the Set. The Set will become an empty Set.
my_set = {'gochocit', True, 5, 'com'}
# Clear my_set
my_set.clear()
print("my_set after clear():", my_set)
Result
my_set after clear(): set()
Using the del keyword
It has the function of completely deleting a Set.
my_set = {'gochocit', True, 5, 'com'}
# Delete my_set
del my_set
# NameError: name 'my_set' is not defined
print("my_set after delete:", my_set)
When a variable my_set is deleted and reused, it will cause an error NameError
.