Exploring Sets in Python: Usage, Comparisons, and Operations

What is Set in Python?

A set is a collection of elements that can be iterated over and changed and does not contain duplicate elements or an index. Sets let you store multiple items in a single variable.

Sets are one of the four built-in data types in Python, along with Lists, Tuples, and dictionaries. Each data type has different uses and qualities.

What does set do in Python?

Python sets are useful because they cannot contain duplicate values, making them ideal for eliminating duplicates in lists or tuples, and for performing common math operations like unions and intersections.

Create sets in Python

A set can be created by placing elements inside curly braces {} and separating them with a comma (,), or by using the built-in set() function.

Creating an empty set can be done by using empty curly braces.

Example:

x = {}
y = set(['Python', 'is', 'Fun'])

print(x)
print(y)

Output:

{}
{'Fun', 'Python', 'is'}

Note: Set is an unordered collection of items that is iterable. If you run your code again the list will change positions.

Initialize a Set in Python

You can initialize a set in Python by using set() or putting all of the items (elements) inside curly braces {} and putting a comma between each one.

Example:

# using the Set function
set1 = set(['India', 'Philippines'])
print(set1, 'and the following type is', type(set1))

# using curly braces {}
set1 = {'Hello', 'Hey', 'Hi'}
print(set1, 'and the following type is', type(set1))

Output:

{'Philippines', 'India'} and the following type is <class 'set'>
{'Hello', 'Hi', 'Hey'} and the following type is <class 'set'>

Modifying a set in Python

To modify a set in Python, you can use the add() method to add one element at a time, or the update() method to add several elements at once.

The update() method can be used with tuples, lists, strings, or other sets.

Example:

# initialize set1
set1 = {1, 3}
print(set1)

# add an element
set1.add(2)
print(set1)

# add multiple elements
set1.update([2, 3, 4])
print(set1)

# add list and set
set1.update([4, 5], {1, 6, 7})
print(set1)

Output:

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

Removing Elements from a Set

Use the remove() or discard() method to remove elements from a set.

The discard() function does nothing if an element is not in a set, while the remove() function will throw an error if the element is not present.

Example:

set1 = {'Prince', 'Adones', 'Jude', 'Paul', 'Ted', 'Glen', 'Jaymar'}

set1.discard('Adones')
print('using discard',set1) # discard an element

set1.remove('Ted')
print('using remove',set1) # remove an element

Output:

using discard {'Paul', 'Ted', 'Jaymar', 'Prince', 'Glen', 'Jude'}
using remove {'Paul', 'Jaymar', 'Prince', 'Glen', 'Jude'}

We can remove an item from a set using the pop() method. Since sets are unordered, we can’t predict which item will be removed.

We can also clear a set of all its items using the clear() method.

Example:

set1 = {'Prince', 'Adones', 'Jude', 'Paul', 'Ted', 'Glen', 'Jaymar'}

print(set1.pop()) # pop an random element

# clear set1
set1.clear()
print('After clearing:',set1) # this will empty the set

Output:

Jaymar
After clearing: set()

Python Set Operations

Python sets can be operated using union, intersection, difference, and symmetric difference. These operations can be performed using either operators or methods.

A = {1, 2, 3, 4, 5}
B = {5, 6, 7, 8, 9}

The list below shows the description of Python Set Operations and their diagrams with examples:

Set Union

Set Union – is a set that has all the elements from both sets.

What is Set in Python with Examples
Set Union Diagram

The | operator and the union() method are used to make a union.

A = {1, 2, 3, 4, 5}
B = {5, 6, 7, 8, 9}

# using the | operator
print (A | B)

# using the union function
print (A.union(B))

Result:

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

Set Intersection

Set Intersection – is a set of elements that are in both A and B.

What is Set in Python with Examples
Set Intersection Diagram

The & operator and the intersection() method are used to make an intersection.

A = {1, 2, 3, 4, 5}
B = {5, 6, 7, 8, 9}

# using the & operator
print (A & B)

# using the intersection function
print (A.intersection(B))

Result:

{5}
{5}

Set Difference

Set Difference – is a set of elements that are only in set A and not in set B. In the same way, B – A is a set of elements that are in B but not in A.

What is Set in Python with Examples
Set Difference Diagram

The - operator and the difference() method are used to make a difference.

A = {1, 2, 3, 4, 5}
B = {5, 6, 7, 8, 9}

# using the - operator on A
print (A - B)

# using the - operator on B
print (B - A)

# using the difference function on A
print (A.difference(B))

# using the difference function on B
print (B.difference(A))

Result:

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

Set Symmetric Difference

Set Symmetric Difference – a set of elements in A and B that aren’t in B (excluding the intersection).

What is Set in Python with Examples
Set Symmetric Difference Diagram

The ^ operator and the symmetric_difference() method are used to make a symmetric difference.

A = {1, 2, 3, 4, 5}
B = {5, 6, 7, 8, 9}

# using the ^ operator on A
print (A ^ B)

# using the symmetric_difference function
print (A.symmetric_difference (B))

Result:

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

Python Set Functions

In the table below, you’ll find a list of Python Set Functions that are commonly used with sets to do different tasks.

FunctionDescription
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 Set Functions

Python Set Methods

Python has many Set Methods and we’ve already talked about some of them. Here is a list of all the ways that set objects can be used:

MethodsDescription
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
Python Set Methods

List vs Set in Python

Sets vs. lists in Python differ primarily in their ability to store unique elements. Sets only store unique values and automatically eliminate duplicates, while lists preserve the order of elements and allow duplicates.

If you need to handle a collection of distinct values or perform efficient membership testing, sets are the ideal choice.

Summary

In this tutorial, we have comprehended the set data type in Python. This includes what sets are, and why you would use them. We have also seen some examples of set operations.

I hope this lesson has helped you understand what is a set in Python and its uses. If you missed any of our previous lessons, check out our list of Python tutorials for absolute beginners.


Leave a Comment