Python Set

Python set is an unordered collection of items which are unique within that set. The order in which item in sets is placed is undefined. Sets are enclosed in brackets {} with items comma separated. Set is a mutable data type, so we can add or remove items from a set.

How to create a set in Python?

Set in Python is created using curly brackets {} with the items in the set be separated by a comma (,).  A set can have any number of items and can be of different data types. To have an idea of python data types, please refer to this tutorial:- Python Datatypes.

Let’s explore some of the examples of the set in the following example:-

The output of the above program is:-

a = {1, 2, 3, 4, 5}
{‘Wednesday’, ‘Friday’, ‘Thursday’, ‘Tuesday’, ‘Saturday’, ‘Monday’, ‘Sunday’}
<class ‘set’>
To create an empty set, initializing it with {} will not work, as it will create a dictionary in python. So, we need to call set() function to assign an empty set in Python.

How to change or add elements to a set in Python?

Since sets are mutable data types, you can add, edit or delete every item in a set. As a set is not indexable in Python, we cannot access any particular index of the item, so we need a function to add an item to set. We can add a single item using add() method and multiple using update() method in the set.

It gives the following output:-
Current set {‘Monday’, ‘Sunday’}
New set {‘Monday’, ‘Sunday’, ‘Tuesday’}
New set {‘Thursday’, ‘Friday’, ‘Tuesday’, ‘Wednesday’, ‘Monday’, ‘Sunday’}

 How to delete or remove elements from a set in Python?

We can use discard() or remove() function to remove the item from a set. discard() function doesn’t throw error if the item is not found, whereas remove() function throws an error if the item is not found.

Current set {‘Saturday’, ‘Friday’, ‘Tuesday’, ‘Sunday’, ‘Wednesday’, ‘Monday’, ‘Thursday’}
Updated set {‘Saturday’, ‘Friday’, ‘Tuesday’, ‘Wednesday’, ‘Monday’, ‘Thursday’}

How to iterate over a Set in Python?

A set can be iterated using for loop. Let us see the following example:-

Tuesday
Saturday
Monday
Sunday
Wednesday
Thursday
Friday

What is Python Frozenset?

Frozenset is an immutable set where set once defined cannot be changed. Sets are unhashable, so they can’t be used as dictionary keys. Frozensets are hashable and can be used as keys to a dictionary. This datatype supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). There are no methods as add or remove elements in a set. We can initialize frozen set as below:-

What are Python Set Operations?

OperatorDescription
A | B
A.union(B)
Returns a set which is the union of sets A and B.
A |= B
A.update(B)
Adds all elements of array B to the set A.
A & B
A.intersection(B)
Returns a set which is the intersection of sets A and B.
A &= B
A.intersection_update(B)
Leaves in the set A only items that belong to the set B.
A – B
A.difference(B)
Returns the set difference of A and B (the elements included in A, but not included in B).
A -= B
A.difference_update(B)
Removes all elements of B from the set A.
A ^ B
A.symmetric_difference(B)
Returns the symmetric difference of sets A and B (the elements belonging to either A or B, but not to both sets simultaneously).
A ^= B
A.symmetric_difference_update(B)
Writes in A the symmetric difference of sets A and B.
A <= B
A.issubset(B)
Returns true if A is a subset of B.
A >= B
A.issuperset(B)
Returns true if B is a subset of A.
A >= B
A.issuperset(B)
Returns true if B is a subset of A.
A < BEquivalent to A <= B and A != B
A > BEquivalent to A >= B and A != B

Let’s use some examples to get an idea on set operations:-

{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}

What are Python Set Built-in functions?

Python provides the following built-in functions which can be used with the sets.

FunctionDescription
all()Return True if all elements of the set are true (or if the set is empty).
any()Return True if any element of the set is true. If the set is empty, return False.
enumerate()Return an enumerated object. It contains the index and value of all the items of a set as a pair.
len()Return the length (the number of items) in the set.
max()Return the largest item in the set.
min()Return the smallest item in the set.
sorted()
Return a new sorted list from elements in the set(does not sort the set itself).
sum()Return the sum of all elements in the set.

What are Python Set built-in methods?

Python provides various methods that can help you perform the various operations in a set. Following are some of the built-in sets methods:-

MethodDescription
add()Adds an element to the set
clear()Removes all elements from the set
copy()Returns a copy of the set
difference()Returns the difference of two or more sets as a new set
difference_update()Removes all elements of another set from this set
discard()Removes an element from the set if it is a member. (Do nothing if the element is not in set)
intersection()Returns the intersection of two sets as a new set
intersection_update()Updates the set with the intersection of itself and another
isdisjoint()Returns True if two sets have a null intersection
issubset()Returns True if another set contains this set
issuperset()Returns True if this set contains another set
pop()Removes and returns an arbitrary set element. Raise KeyError if the set is empty
remove()Removes an element from the set. If the element is not a member, raise a KeyError
symmetric_difference()Returns the symmetric difference of two sets as a new set
symmetric_difference_update()Updates a set with the symmetric difference of itself and another
union()Returns the union of sets in a new set
update()Updates the set with the union of itself and others

 

SHARE Python Set

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Share