Sets

In this lecture, you'll learn everything about Python sets; how they are created, adding or removing elements from them, and all operations performed on sets in Python.

A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed).

However, a set itself is mutable. We can add or remove items from it.

Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.


Creating Python Sets

A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set() function.

It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.

# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Output

{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}

Try the following examples as well.

Output

Creating an empty set is a bit tricky.

Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements, we use the set() function without any argument.

Output

Modifying a set in Python

Sets are mutable. However, since they are unordered, indexing has no meaning.

We cannot access or change an element of a set using indexing or slicing. Set data type does not support it.

We can add a single element using the add() method, and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.


Removing elements from a set

A particular item can be removed from a set using the methods discard() and remove().

The only difference between the two is that the discard() function leaves a set unchanged if the element is not present in the set. On the other hand, the remove() function will raise an error in such a condition (if element is not present in the set).

The following example will illustrate this.

Output

Similarly, we can remove and return an item using the pop() method.

Since set is an unordered data type, there is no way of determining which item will be popped. It is completely arbitrary.

We can also remove all the items from a set using the clear() method.

Output


Python Set Operations

Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. We can do this with operators or methods.

Let us consider the following two sets for the following operations.

Set Union

Set Union in Python

Union of A and B is a set of all elements from both sets.

Union is performed using | operator. Same can be accomplished using the union() method.

Output

Try the following examples on Python shell.

Set Intersection

Intersection of A and B is a set of elements that are common in both the sets.

Intersection is performed using & operator. Same can be accomplished using the intersection() method.

Output

Try the following examples on Python shell.

Set Difference

Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of elements in B but not in A.

Difference is performed using - operator. Same can be accomplished using the difference() method.

Output

Try the following examples on Python shell.

Set Symmetric Difference

Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding the intersection).

Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric_difference()`.

Output

Try the following examples on Python shell.

Other Python Set Methods

There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with the set objects:

Method
Description

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. Raises KeyError if the set is empty

remove()

Removes an element from the set. If the element is not a member, raises 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

Other Set Operations

Set Membership Test

We can test if an item exists in a set or not, using the in keyword.

Output

Iterating Through a Set

We can iterate through each item in a set using a for loop.

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

all()

Returns True if all elements of the set are true (or if the set is empty).

any()

Returns True if any element of the set is true. If the set is empty, returns False.

enumerate()

Returns an enumerate object. It contains the index and value for all the items of the set as a pair.

len()

Returns the length (the number of items) in the set.

max()

Returns the largest item in the set.

min()

Returns the smallest item in the set.

sorted()

Returns a new sorted list from elements in the set(does not sort the set itself).

sum()

Returns the sum of all elements in the set.

Python Frozenset

Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozensets are immutable sets.

Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand, frozensets are hashable and can be used as keys to a dictionary.

Frozensets can be created using the frozenset() function.

This data type supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). Being immutable, it does not have methods that add or remove elements.

Last updated

Was this helpful?