Python Sets

A set in Python is an unordered collection of items. Python sets are mutable in nature. Which means that sets can be changed after creation. However, set items should be immutable.

A set can not have duplicate items. Even if you pass duplicate items, set itself removes all duplicates items from it.


Creating a set in Python

A set can be created either using curly braces directly or using an inbuilt function set().

  1. Using curly braces directly
  2. Using inbuilt function set()

1. Using curly braces:

In this method, we can create a set by placing all the set items inside curly braces {} and separating each set item by a comma. Each item in the set should be immutable in nature. See the example below:

# A program to create a set in Python

number_set = {1, 2, 3, 4, 5, 6}
print('A set of Numbers: ', number_set)

fruits_set = {'Apple', 'Mango', 'Orange', 'Grapes'}
print('nA set of Fruits: ', fruits_set)

Output:

A set of Numbers:  {1, 2, 3, 4, 5, 6}

A set of Fruits:  {'Grapes', 'Mango', 'Apple', 'Orange'}

2. Using inbuilt function set()

# A program to create a set in Python using the inbuilt function set()

number_set = set([1, 2, 3, 4, 5])
print('A set of numbers: ', number_set)

fruits_set = set(['Apple', 'Mango', 'Orange', 'Grapes'])
print('nA set of fruits: ', fruits_set)

Output:

A set of numbers:  {1, 2, 3, 4, 5}

A set of fruits:  {'Orange', 'Apple', 'Mango', 'Grapes'}

Creating an empty set

We can not use empty curly braces directly to create an empty set. Empty curly braces actually create an empty dictionary in Python. So if we want to create an empty set we can use the inbuilt function set(). See the example below:

# A program to create an empty set in Python

a = {}           # It's actually an empty dictionary
print(type(a))

b = set()        # An empty set
print(type(b))

Output:

<class 'dict'>
<class 'set'>

Accessing set items:

As we know sets are unordered objects. Therefore, we can not predict in which order set items are arranged. Because of this reason, we can not use indexing to access a particular item in the set. However, we can use the for loop to access all the set items at a time. See the example below:

# A program to access set items in Python

fruit_set = {'Apple', 'Mango', 'Orange', 'Grapes'}

for fruit in fruit_set:
    print(fruit)

Output:

Mango
Grapes
Apple
Orange

Adding elements to a set

Sets are mutable in nature. Therefore, we can add new items to a set. We can use the add() function to add a single item to a set. If we want to add multiple items at a time then we can use the inbuilt function update().

The update() function can take lists, tuples, dictionaries, etc as input parameters.

# A program to add new items to a set in Python

number_set = {1, 2}
print('Initial Set: ', number_set)

number_set.add(3)
print('nAfter add(3): ', number_set)

number_set.update([4, 5, 6, 7])
print('nAfter update([4, 5, 6, 7]) : ', number_set)

number_set.update({8, 9})
print('nAfter update({8, 9}): ',number_set)

Output:

Initial Set:  {1, 2}

After add(3):  {1, 2, 3}

After update([4, 5, 6, 7]) :  {1, 2, 3, 4, 5, 6, 7}

After update({8, 9}):  {1, 2, 3, 4, 5, 6, 7, 8, 9}

Removing elements from a set

Python provides us with two inbuilt methods to remove elements from a set.

  1. discard() function
  2. remove() function

The only difference between these two functions is that the discard() function will not throw an error if the item to be removed does not exist in the set while the remove() function generates an error if the item does not exist.


1. Using discard() function

# A program to explain the discard() function in Python sets

month_set = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'}

print('Original Set: ', month_set)

# Remove Jan from set
month_set.discard('Jan')
print('nAfter removing Jan: ',month_set)

# Removing a non existing item
month_set.discard('Apple')
print('nRemoving non existing item: ', month_set)

Output:

Original Set:  {'Jun', 'Feb', 'Apr', 'Jan', 'May', 'Mar'}

After removing Jan:  {'Jun', 'Feb', 'Apr', 'May', 'Mar'}

Removing non existing item:  {'Jun', 'Feb', 'Apr', 'May', 'Mar'}

2. Using the remove() function

The remove() function will throw an error if the item to be removed does not exist in the set.

# A program to explain the remove() function in Python set

num_set = {1, 2, 3, 4, 5, 6}

print('Initial set: ', num_set)

# Remove 5 from set
num_set.remove(5)
print('nAfter removing 5 from the set: ',)
print(num_set)

# Removing non existing item
num_set.remove(8)
print('nAfter removing non exising item: ')
print(num_set)

Output:

Initial set:  {1, 2, 3, 4, 5, 6}

After removing 5 from the set: 
{1, 2, 3, 4, 6}

Traceback (most recent call last):
  File "jdoodle.py", line 13, in <module>
    num_set.remove(8)
KeyError: 8

Clearing all items

Inbuilt function clear() can be used to completely clear/empty a set.

# A program to explain clear() function in Python sets

num_set = {1, 2, 3}

print('Initial Set: ', num_set)

# Clearing all items
num_set.clear()
print('nAfter clearing all items: ')
print(num_set)

Output:

Initial Set:  {1, 2, 3}

After clearing all items: 
set()

Python set operations

Python sets can be used to perform mathematical operations like union, intersection, difference, etc. Python provides us inbuilt operators and methods to perform such operations. These operations are as follows:

  1. Union of two sets
  2. Intersection of two sets
  3. Difference of two sets
  4. Symmetric difference of two sets

Let’s discuss each one


1. Union of two sets

The union of two sets contains all the items which are present in both sets and no item is repeated.

Union of two sets in Python

The union of two sets can be performed either using the OR operator | or using the inbuilt function union(). The result of both methods is always the same.

# A program to demonstrate the union of two sets in Python

setA = {1, 2, 3, 4, 5, 6}
setB = {4, 5, 6, 7, 8}

# Union using | operator 
print('Union using | operator: ', setA | setB)

# Union using the union() function
print('nUnion using the union() function: ', setA.union(setB))

Output:

Union using | operator:  {1, 2, 3, 4, 5, 6, 7, 8}

Union using the union() function:  {1, 2, 3, 4, 5, 6, 7, 8}

2. Intersection of two sets

The intersection of two sets contains only those elements which are common in both sets.

Intersection of two sets in Python

The intersection of two sets can be calculated either using the AND operator & or using the inbuilt function intersection().

# A program to demonstrate the intersection of two sets in Python

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

# Intersection using AND operator(&) 
print('Intersection using & operator: ', setA & setB)

# Intersection using the intersection() function
print('nIntersection using the intersection() function: ', setA.intersection(setB))

Output:

Intersection using & operator:  {4, 5, 6}

Intersection using the intersection() function:  {4, 5, 6}

3. Difference of two sets

The difference of two sets A and B i.e A – B contains all the items of set A which are not present in the set B.

Difference of two sets in Python

The difference of two sets can be obtained either using the subtraction operator (-) or using the inbuilt function difference(). Both methods give the same result.

# A program to demonstrate the difference of two sets in Python

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

# Difference using subtraction operator(-) 
print('Difference using - operator: ', setA-setB)

# Difference using the difference() function
print('nDifference using the difference() function: ', setA.difference(setB))

Output:

Difference using - operator:  {1, 2, 3}

Difference using the difference() function:  {1, 2, 3}

4. Symmetric difference of two sets

The symmetric difference of two sets contains all the items which are not common in both sets. It means, it is just opposite to the intersection of two sets which contains all common items.

Symmetric difference of two sets in Python

The symmetric difference of two sets can be calculated using the XOR operator (^). The inbuilt function symmetric_difference() can also be used to get the same result.

# A program to demonstrate the symmetric difference of two sets in Python

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

# Symmetric difference using XOR operator(^) 
print('Using ^ operator: ', setA^setB)

# Symmetric Difference using the symmetric_difference() function
print('nUsing the symmetric_difference() function: ', setA.symmetric_difference(setB))

Output:

Using ^ operator:  {1, 2, 3, 7, 8, 9}

Using the symmetric_difference() function:  {1, 2, 3, 7, 8, 9}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts

Leave a Comment