Python has four built-in data types data, list, tuple, dictionary, and set. These data types can store multiple collections of data.
A list is an ordered collection of data, it is a type of array that can store duplicate values, it is dynamic in size and mutable, and its elements can be accessed with their index. A tuple is also similar to a list but unlike the list, it is not mutable. A dictionary is also similar but it contains key-value pairs. On the other hand, a set is an unordered collection of data, it is iterable and mutable, and the key property is that it has no duplicate elements.
This tutorial will cover all the fundamental things you must know about a set in Python.
Python Set
A Python set is an unordered and unindexed collection of elements.
- Every element is unique.
- The set contains elements that are unordered.
- No duplicates are allowed.
- The set itself is mutable i.e. one can add/remove items(elements) from it.
- Unlike arrays, wherein the elements are stored in order, the order of elements in a set is not defined.
- The elements in the set are not stored in their order of appearance in the set.
Creating a Set
Set can be created by placing all the elements within curly braces {}, separated by a comma. They can also be created by using the built-in set() constructor.
The elements can be of different data types, but a set doesn’t support mutable elements. Sets are unordered, so one can’t be sure of the order of elements in which they will appear.
Example 1: Creating a Set using Curly Braces
Let’s pass some fruit’s names inside curly braces {}, assigned it to a variable, and print that variable.
Fruits = {"apple", "banana", "cherry","apple"} # Set contains different fruits
print(Fruits)
Output:
{‘apple’, ‘banana’, ‘cherry’}
Here you can see that the duplicate values are automatically removed which is one of the key properties of a set, hence the output is justified.
Example 2: Creating a Set using the set() Constructor
We have a list that contains days of the week, and some elements occur twice, let’s pass this list inside the set() constructor to see whether it converts the list into a set and removes all duplicates.
Days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Tuesday", "Wednesday", "Saturday", "Sunday"] # List contains days of week
daysSet = set(Days) # Convert list to set
print(daysSet)
Output:
{‘Monday’, ‘Thursday’, ‘Friday’, ‘Tuesday’, ‘Sunday’, ‘Wednesday’, ‘Saturday’}
Here you can see that we got a set as an output and duplicate values are removed.
Recommended Readings:
Access elements from a Set
Since python sets are unordered and unindexed, one cannot access the elements by referring to their index, unlike arrays.
The elements of a set can be accessed by Iterating through them using a for
loop.
Example: Accessing elements from a Set
We have a set containing various fruits, let’s print its elements one by one using for loop.
Fruits = {"apple", "mango", "cherry"}
for a in Fruits:
print(a)
Output:
mango
cherry
apple
Here we got each element one by one, if you re-run the program, the order in which these elements print will change because a set store data in an unordered form.
Checking elements in a Set
We can check for a particular element that whether it exists in a set using the in
keyword.
If the element exists, it will return true, and if not then false.
Example:
Again, we have a set containing various fruits, let’s check for some fruits that it exists or not.
Fruits = {"apple", "banana", "cherry","apple"} # Set contains different fruits
result = "apple" in Fruits # Check if "apple" is present in the set
print(result)
result2 = "orange" in Fruits # Check if "orange" is present in the set
print(result2)
Output:
True
False
Here for “apple” we get true means it is present in the set and for “orange” it returns false which state that it is not present in the set.
Add elements to a Set
We can add elements to a set by using add()
method. The add()
method takes an element as an argument to add it to the set.
Example: Addition of elements to a Set
Let’s use add() method to add an element “grapes” to the Fruits set and print it.
Fruits = {"apple", "mango", "cherry"}
Fruits.add("grapes")
print(Fruits)
Output:
{'cherry', 'apple', 'mango', 'grapes'}
Here you can see that the element “grapes” is successfully added.
Update elements of a Set
We can use the update()
method to update a set to add elements from any other iterable. The update()
method takes an iterable as an argument to add its elements to the set.
Example: Addition of elements of a list to a set
Let’s use the update() method to add the elements of a list to the Fruits set and print it.
Fruits = {"apple", "mango", "cherry"}
Fruits_list = ["banana", "orange", "strawberry"]
Fruits.update(Fruits_list)
print(Fruits)
Output:
{'strawberry', 'mango', 'orange', 'banana', 'cherry', 'apple'}
Here you can see that the elements of the list are successfully added.
Removal of elements from a Set
We can delete the items from the set using either of the following methods:
- By using
remove()
method - By using
discard()
method - By using
clear()
method – deletes all the elements from the set - By using
del()
method – deletes the entire set
Example 1: Using the remove() method
Fruits = {"apple", "grapes", "cherry"}
Fruits.remove("grapes")
print(Fruits)
Output:
{‘cherry’, ‘apple’}
Example 2: Using the discard() method
Fruits = {"apple", "grapes", "cherry"}
Fruits.discard("grapes")
print(Fruits)
Output:
{‘cherry’, ‘apple’}
Example 3: Using the clear() method
Fruits = {"apple", "grapes", "cherry"}
Fruits.clear()
print(Fruits)
Output:
set()
Example 4: Using the del() method
Fruits = {"apple", "grapes", "cherry"}
del Fruits
print(Fruits)
Output:
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(Fruits)
NameError: name 'Fruits' is not defined
Methods in Sets
Method | Description |
---|---|
add() | Adds an element to the set |
clear() | Removes all the elements from the set |
copy() | Returns a copy of the set |
difference() | Returns a set containing the difference between two or more sets |
difference_update() | Removes the items in this set that are also included in another, specified set |
discard() | Remove the specified item |
intersection() | Returns a set, that is the intersection of two other sets |
intersection_update() | Removes the items in this set that are not present in other, specified set(s) |
isdisjoint() | Returns whether two sets have a intersection or not |
issubset() | Returns whether another set contains this set or not |
issuperset() | Returns whether this set contains another set or not |
pop() | Removes an element from the set |
remove() | Removes the specified element |
symmetric_difference() | Returns a set with the symmetric differences of two sets |
symmetric_difference_update() | inserts the symmetric differences from this set and another |
union() | Return a set containing the union of sets |
update() | Update the set with the union of this set and others |
Set Operations in Python
Sets are used to carry out mathematical functionality set operations such as union, difference, intersection, and symmetric difference.
Set Union – Inclusion of all elements from both sets.
Either of the following methods performs union operation:
- By using
|
operator - By using
union()
method
Example: Union of Sets
X = {1, 2, 3}
Y = {6, 7, 8}
print(X | Y)
print(Y.union(X))
Output:
{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}
Set Intersection – Inclusion of elements that are common to both sets.
Either of the following methods performs an intersection operation:
- By using
&
operator - By using
intersection(
) method
Example: Intersection of Sets
X = {1, 2, 3}
Y = {3, 2, 8}
print(X & Y)
print(Y.intersection(X))
Output:
{2, 3}
{2, 3}
Set Difference – Inclusion of elements from either of the sets.
(A – B) contains the elements that are only in set A but not in set B.
(B – A) contains the elements that are only in set B but not in set A.
Either of the following methods performs different operation:
- By using
-
operator - By using
difference()
method
Example: Difference of Sets
X = {1, 2, 3}
Y = {3, 2, 8}
print(X - Y)
print(Y.difference(X))
Output:
{1}
{8}
Set Symmetric Difference – Inclusion of elements from both the sets except the common elements of the sets
Either of the following methods performs symmetric Difference operation:
- By using
^
operator - By using
symmetric_difference()
method
Example: Symmetric Difference of Sets
X = {1, 2, 3, 9, 0}
Y = {3, 2, 8, 7, 5}
print(X ^ Y)
print(Y.symmetric_difference(X))
Output:
{0, 1, 5, 7, 8, 9}
{0, 1, 5, 7, 8, 9}
Summary
In this tutorial we have learned that the set in python is used to store an unordered collection of data, it is iterable, mutable, and has no duplicate elements. A set is created by using the curly braces {} or using the built-in constructor set(). Its element can be assessed using a loop. We can use in
keyword to check for the existence of a particular element. We can also add and remove elements to a set.
Hope this tutorial helps you to understand the sets in Python.
References
- Python Sets
- Python Official Documentation