5.1 Adding an Element
Modifying sets in Python is super easy: basically, you've got 3 options: add an element to a set, remove an element from a set, and check whether an element is in a set.
To add a single element to a set, use the
add()
method. This method adds the element to the set if it's not already there. If the element is present, the set stays unchanged.
Example:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
In this example, the element 4 is added to the set my_set
. If we tried to add an element that's already there, like 2, the set wouldn't change:
my_set = {1, 2, 3, 4}
my_set.add(2)
print(my_set) # Output: {1, 2, 3, 4}
5.2 Adding Multiple Elements
To add several elements to a set, use the
update()
method. This method takes any iterable (list, tuple, string, etc.) and adds all its elements to the current set. If any of the elements to be added are already in the set, they won't be added again.
Example with adding elements from a list
my_set = {1, 2, 3}
my_set.update([4, 5, 6])
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
In this example, all elements from the list [4, 5, 6] are added to the set my_set
.
Example with adding elements from a tuple
my_set = {1, 2, 3}
my_set.update((4, 5, 6))
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
Example with adding elements from a string
Every character in the string will be added to the set as separate elements.
my_set = {'a', 'b', 'c'}
my_set.update('def')
print(my_set) # Output: {'a', 'b', 'c', 'd', 'e', 'f'}
Adding elements from another set
The update()
method can also take another set as an argument. All elements from the second set will be added to the first set.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
print(set1) # Output: {1, 2, 3, 4, 5}
5.3 Practical Application
Here are some neat practical examples of using sets in real life.
Removing Duplicates
Sets automatically remove duplicates, which makes them handy for dealing with lists that have repeat items.
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set) # Output: {1, 2, 3, 4, 5}
Combining Data
Sets can be used to combine data from multiple sources while keeping the elements unique.
set1 = {'apple', 'banana'}
set2 = {'banana', 'cherry'}
set3 = {'cherry', 'date'}
combined_set = set1 | set2 | set3
print(combined_set) # Output: {'apple', 'banana', 'cherry', 'date'}
GO TO FULL VERSION