In Python, sets are versatile data structures used to store unique elements. Unlike lists or tuples, sets do not allow duplicate items. In this guide, we’ll explore the concept of sets, provide easy-to-understand examples, address common questions, and conclude with insights into their significance.
What are Python Sets?
Sets are collections of unique elements, meaning each item appears only once within the set. Sets are unordered, meaning the items are not stored in any specific order.
Example:
Imagine a set of unique numbers:
my_set = {1, 2, 3, 4}
PythonSets are unordered collection of data items. They store multiple items in a single variable. Sets items are separated by commas and enclosed within curly brackets {}. Sets are unchangeable, meaning you cannot change items of the set once created. Sets do not contain duplicate items.
Example:
info = {"Carla", 19, False, 5.9, 19}
print(info)
PythonOutput:
{False, 19, 5.9, 'Carla'}
PythonHere we see that the items of set occur in random order and hence they cannot be accessed using index numbers. Also sets do not allow duplicate values.
Accessing Python Sets Items:
1. Using a For loop
You can access items of set using a for loop.
Example:
info = {"Carla", 19, False, 5.9}
for item in info:
print(item)
PythonOutput:
False
Carla
19
5.9
Python2. Add Set Items
If you want to add a single item to the set use the add() method.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.add("Helsinki")
print(cities)
PythonOutput:
{'Tokyo', 'Helsinki', 'Madrid', 'Berlin', 'Delhi'}
PythonIf you want to add more than one item, simply create another set or any other iterable object(list, tuple, dictionary), and use the update() method to add it into the existing set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Helsinki", "Warsaw", "Seoul"}
cities.update(cities2)
print(cities)
PythonOutput:
{'Seoul', 'Berlin', 'Delhi', 'Tokyo', 'Warsaw', 'Helsinki', 'Madrid'}
Python3. Remove items from Python Sets:
We can use remove() and discard() methods to remove items form list.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.remove("Tokyo")
print(cities)
PythonOutput:
{'Delhi', 'Berlin', 'Madrid'}
PythonExample 2:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.discard("Delhi")
print(cities)
PythonOutput:
{'Berlin', 'Tokyo', 'Madrid'}
PythonThe main difference between remove and discard is that, if we try to delete an item which is not present in set, then remove() raises an error, whereas discard() does not raise any error.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.remove("Seoul")
print(cities)
PythonOutput:
KeyError: 'Seoul'
PythonExample 2:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.discard("Seoul")
print(cities)
PythonOutput:
{'Madrid', 'Delhi', 'Tokyo', 'Berlin'}
PythonThere are various other methods to remove items from the set: pop(), del(), clear().
1. pop():
This method removes the last item of the set but the catch is that we don’t know which item gets popped as sets are unordered. However, you can access the popped item if you assign the pop() method to a variable.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
item = cities.pop()
print(cities)
print(item)
PythonOutput:
{'Tokyo', 'Delhi', 'Berlin'}
Madrid2.
Python2. del:
del is not a method, rather it is a keyword which deletes the set entirely.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
del cities
print(cities)
PythonOutput:
NameError: name 'cities' is not defined
PythonWe get an error because our entire set has been deleted and there is no variable called cities which contains a set.
What if we don’t want to delete the entire set, we just want to delete all items within that set?
3. clear():
This method clears all items in the set and prints an empty set.
Example:
= {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.clear()
print(cities)
PythonOutput:
set()
PythonCheck if item exists
You can also check if an item exists in the set or not.
Example 1:
info = {"Carla", 19, False, 5.9}
if "Carla" in info:
print("Carla is present.")
else:
print("Carla is absent.")
PythonOutput:
Carla is present.
PythonExample 2:
info = {"Carla", 19, False, 5.9}
if "Carmen" in info:
print("Carmen is present.")
else:
print("Carmen is absent.")
PythonOutput:
Carmen is absent.
PythonJoin Sets
Sets in python more or less work in the same way as sets in mathematics. We can perform operations like union and intersection on the sets just like in mathematics.
1. Union() and Update() in Python Sets
The union() and update() methods prints all items that are present in the two sets. The union() method returns a new set whereas update() method adds item into the existing set from another set.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.union(cities2)
print(cities3)
PythonOutput:
{'Tokyo', 'Madrid', 'Kabul', 'Seoul', 'Berlin', 'Delhi'}
PythonExample 2:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.update(cities2)
print(cities)
PythonOutput:
{'Berlin', 'Madrid', 'Tokyo', 'Delhi', 'Kabul', 'Seoul'}
Python2. Intersection and Intersection_update() in Python Sets
The intersection() and intersection_update() methods prints only items that are similar to both the sets. The intersection() method returns a new set whereas intersection_update() method updates into the existing set from another set.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.intersection(cities2)
print(cities3)
PythonOutput:
{'Madrid', 'Tokyo'}
PythonExample 2:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.intersection_update(cities2)
print(cities)
PythonOutput:
{'Tokyo', 'Madrid'}
Python3. symmetric_difference and symmetric_difference_update() in Python Sets
The symmetric_difference() and symmetric_difference_update() methods prints only items that are not similar to both the sets. The symmetric_difference() method returns a new set whereas symmetric_difference_update() method updates into the existing set from another set.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.symmetric_difference(cities2)
print(cities3)
PythonOutput:
{'Seoul', 'Kabul', 'Berlin', 'Delhi'}
PythonExample 2:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.symmetric_difference_update(cities2)
print(cities)
PythonOutput:
{'Kabul', 'Delhi', 'Berlin', 'Seoul'}
Python4. difference() and difference_update():
The difference() and difference_update() methods prints only items that are only present in the original set and not in both the sets. The difference() method returns a new set whereas difference_update() method updates into the existing set from another set.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul", "Delhi"}
cities3 = cities.difference(cities2)
print(cities3)
PythonOutput:
{'Tokyo', 'Madrid', 'Berlin'}
PythonExample 2:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul", "Delhi"}
print(cities.difference(cities2))
PythonOutput:
{'Tokyo', 'Berlin', 'Madrid'}
PythonSet Methods
Apart from the methods we discussed earlier in the chapter there are some more methods that we can use to manipulate sets.
What if you want to check if items of a particular set are present in another set?
There are a few methods to check this.
i. isdisjoint():
The isdisjoint() method checks if items of given set are present in another set. This method returns False if items are present, else it returns True.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
print(cities.isdisjoint(cities2))
PythonOutput:
False
PythonExample 2:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul"}
print(cities.isdisjoint(cities2))
PythonOutput:
True
Pythonii. issuperset():
The issuperset() method checks if all the items of a particular set are present in the original set. It returns True if all the items are present, else it returns False.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul"}
print(cities.issuperset(cities2))
cities3 = {"Seoul", "Madrid","Kabul"}
print(cities.issuperset(cities3))
PythonOutput:
False
False
PythonExample 2:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Delhi", "Madrid"}
print(cities.issuperset(cities2))
PythonOutput:
True
Pythoniii. issubset():
The issubset() method checks if all the items of the original set are present in the particular set. It returns True if all the items are present, else it returns False.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Delhi", "Madrid"}
print(cities2.issubset(cities))
PythonOutput:
True
PythonExample 2:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul"}
print(cities2.issubset(cities))
cities3 = {"Seoul", "Madrid", "Kabul"}
print(cities3.issubset(cities))
PythonOutput:
False False
PythonConclusion
Python sets are powerful data structures for managing collections of unique elements. They provide efficient methods for adding, removing, and performing set operations, making them valuable tools in various programming scenarios. By understanding sets and their capabilities, you can simplify complex problems and streamline your code. Embrace sets when you need to work with unique data sets and leverage their efficiency to enhance the performance and clarity of your Python programs.
Frequently Asked Questions
Ans: No, sets only contain unique elements. If you try to add a duplicate element, it will not be added.
Q2. Are Sets Ordered?
Ans: No, sets are unordered, meaning the elements are not stored in any specific order.
Q3. What’s the Difference Between
remove()
and discard()
? Ans:The remove()
method raises an error if the element is not present in the set, while the discard()
method does not raise an error.