βΊοΈSets
A set is an unordered collection of unique elements in Python. The elements can be of any data type, but they must be immutable (i.e., they cannot be changed). Sets are mutable, which means that you can add, remove, and update their elements after they have been created.
In Python, sets are defined using curly braces {}
or the built-in set()
function.
Creating a Set
To create a set, you can define a comma-separated list of elements inside curly braces {}
or use the set()
function with a list of elements as an argument.
Here's an example of how to create a set:
As you can see, the elements in a set are not ordered in any particular way.
Create an Empty Set in Python
To create an empty set in Python, you can use either of the following ways:
Using curly braces {}:
Here, the empty curly braces {}
actually create an empty dictionary instead of an empty set.
Using the
set()
function:
Here, we use the set()
function to create an empty set.
Note: To create a set with at least one element, we should enclose the elements in curly braces {}
or use the set()
function.
Duplicate Items in a Set
In a set, duplicate items are not allowed. If we try to add a duplicate item to a set, it will not be added and the set will remain unchanged.
For example:
In the above example, we try to add the value 5
to the set my_set
twice, but it only gets added once. When we try to add the value 6
, it gets added to the set since it is not a duplicate item.
Accessing Set Elements
Since sets are unordered, you cannot access their elements by index. Instead, you can loop through the set using a for
loop or check if an element is in the set using the in
keyword.
Here's an example:
Modifying Sets
You can add, remove, or update elements in a set after it has been created.
Adding Elements to a Set
To add an element to a set, you can use the add()
method or the update()
method to add multiple elements.
Here's an example:
Removing Elements from a Set
To remove an element from a set, you can use the remove()
method or the discard()
method. The only difference between the two methods is that if you try to remove an element that is not in the set, the remove()
method will raise a KeyError
exception, while the discard()
method will not.
Here's an example:
Updating Elements in a Set
To update an element in a set, you can use the update()
method or the add()
method.
The update()
method is used to add multiple items to a set at once. It takes an iterable as an argument and adds each element of the iterable to the set. If any of the elements already exist in the set, they are ignored.
Here's an example of using the update()
method to add multiple elements to a set:
Output:
The add()
method, on the other hand, is used to add a single element to a set. If the element already exists in the set, it is ignored.
Here's an example of using the add()
method to add a single element to a set:
Output:
You can also update a set with another set using the update()
method:
Output:
Built-in Functions with Set
Built-in functions like all()
, any()
, enumerate()
, len()
, max()
, min()
, sorted()
, sum()
etc. are commonly used with sets to perform different tasks.
Function | Description |
---|---|
len() | Returns the length (number of items) in a set |
max() | Returns the maximum value of a set |
min() | Returns the minimum value of a set |
any() | Returns True if any item in the set is true. If the set is empty, returns False. |
all() | Returns True if all items in the set are true. If the set is empty, returns True. |
set() | Constructs a new set from an iterable (list, tuple, string, etc.) |
sorted() | Returns a new sorted list from the items in a set |
sum() | Returns the sum of all elements in a set |
pop() | Removes and returns an arbitrary item from the set |
clear() | Removes all elements from the set |
copy() | Returns a shallow copy of the set |
isdisjoint() | Returns True if two sets have no intersection |
issubset() | Returns True if all items in the set are present in another set |
issuperset() | Returns True if a set contains all the items in another set |
union() | Returns a new set with all items from both sets |
intersection() | Returns a new set with items common to both sets |
difference() | Returns a new set with items in one set but not the other |
symmetric_difference() | Returns a new set with items in either set, but not both sets |
Iterate Over a Set in Python
You can iterate over a set in Python using a for
loop. Here's an example:
Output:
Note that the order of the elements in the set may vary when you iterate over it.
Find Number of Set Elements
To find the number of elements in a set in Python, you can use the built-in len()
function.
Here's an example:
In the above example, we have a set my_set
with 5 elements. We use the len()
function to find the number of elements in the set and print the output, which is 5.
Set Operations
Python Set provides different built-in methods to perform mathematical set operations like union, intersection, subtraction, and symmetric difference.
Union of Two Sets
The union of two sets in Python can be obtained using the union()
method or the pipe operator |
. Here's an example:
In the above example, we have two sets set1
and set2
. We can obtain the union of these two sets by calling the union()
method on set1
and passing set2
as an argument. We can also use the pipe operator |
to perform the union operation on these two sets. The result of both approaches is the same set {1, 2, 3, 4, 5}
.
Set Intersection
Set Intersection means the common elements in both sets.
In Python, the intersection of two sets can be found using the intersection()
method or the &
operator.
Here's an example:
In the above example, we have two sets, set1
and set2
, and we are finding their intersection using the intersection()
method and the &
operator. The resulting set contains the common elements in both sets, which are 4 and 5.
Check if two sets are equal
Output:
To check if two sets are equal, you can use the ==
operator. Here's an example:
Other Python Set Methods
Here are some other commonly used methods in Python sets:
add(element)
: Adds an element to the set.remove(element)
: Removes an element from the set. Raises a KeyError if the element is not found.discard(element)
: Removes an element from the set. Does not raise an error if the element is not found.pop()
: Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty.clear()
: Removes all elements from the set.copy()
: Returns a copy of the set.intersection_update(other_set)
: Updates the set with the intersection of itself and another set.difference_update(other_set)
: Updates the set with the difference of itself and another set.symmetric_difference_update(other_set)
: Updates the set with the symmetric difference of itself and another set.update(other_set)
: Updates the set by adding elements from another set.
These methods modify the set in place and do not return a new set.
Last updated