Python Set

A Python set data type is similar to Lists. However, Sets does not accept duplicate items (unique values). The Python set is an unordered collection of zero or more items, which are unindexed (no index position). Python Sets allows mutable items, so adding and removing items in a set is very easy. However, set slicing is not possible in Python because of no index. Generally, Python sets are very useful to perform mathematical operations like Union, Intersections, set comparisons, and set differences.

Python set Declaration

A set is created by placing the required items inside curly braces or using the set() function without any arguments. Sets allow you to place different kinds of data type items like integer, string, etc., in a single set. The following are the available list of ways to declare sets in Python.

# set Declaration

# Empty set
mySet = {}
mySet = set()

# Set with Integer Keys
mySet = {1, 2, 3, 4, 5}

# Set with String Keys
mySet = {'apple', 'kiwi', 'banana', 'orange'}

# Set with Mixed Data Types
mySet = {1, 2, 1.5, 2.5, 'apple'}
mySet = {'banana', 1, 2, (1, 2, 3)}

# Python Set using set()
mySet = set([1, 2, 3, 4, 5])
mySet = set((1, 2, 3, 4, 5, 6, 7))
            
# set() example 2
mySet = (['apple', 'kiwi', 'banana', 'orange'])
mySet = (('apple', 'kiwi', 'banana', 'orange'))

Python set Example

Let me declare a few sets and print them. It helps to understand the concept of sets in Python.

# set Declaration

# Empty set
mySet1 = {}
mySet2 = set()

# Set with Integer Keys
mySet3 = {1, 2, 3, 4, 5}

# Set with String Keys
mySet4 = {'apple', 'kiwi', 'banana', 'orange'}

print(mySet1)
print(mySet2)
print(mySet3)
print(mySet4)
{}
set()
{1, 2, 3, 4, 5}
{'apple', 'kiwi', 'orange', 'banana'}

Python Mixed Sets Example

We can create a set with multiple data types. In this example, we declare a set with mixed data types. Next, we use the set() to declare a set

# Python set Declaration

# Set with Mixed Data Types
mySet1 = {1, 2, 1.5, 2.5, 'apple'}
mySet2 = {'banana', 1, 2, (1, 2, 3)}

print(mySet1)
print(mySet2)

# Python Set using set()
mySet3 = set([1, 2, 3, 4, 5])
mySet4 = set((1, 2, 3, 4, 5, 6, 7))

print(mySet3)
print(mySet4)

# set() example 2
mySet5 = (['apple', 'kiwi', 'banana', 'orange'])
mySet6 = (('apple', 'kiwi', 'banana', 'orange'))

print(mySet5)
print(mySet6)

Output of creating mixed sets

{1, 2, 2.5, 1.5, 'apple'}
{1, 2, (1, 2, 3), 'banana'}
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 7}
['apple', 'kiwi', 'banana', 'orange']
('apple', 'kiwi', 'banana', 'orange')

set {} vs set()

This Python example show the difference between {} and set() while declaring a set.

# Python set Declaration

# {} Vs set()
mySet = {'TutorialGateway'}
mySet1 = set('TutorialGateway')

print(mySet)
print(mySet1)

mySet2 = {123456}
mySet3 = set('123456')

print(mySet2)
print(mySet3)

set {} vs set() output

{'TutorialGateway'}
{'o', 'y', 'e', 't', 'u', 'G', 'l', 'T', 'a', 'r', 'i', 'w'}
{123456}
{'3', '1', '4', '6', '2', '5'}

Convert List to Set

By adding the curly braces before and after the list, you can convert the List to a Set.

# Python set Declaration

# List to Set
mySet = [1, 2, 3]
print(mySet)
print({mySet})

Converting List to Set output

[1, 2, 3]
Traceback (most recent call last):
  File "/Users/suresh/Desktop/simple.py", line 4, in <module>
    print({mySet})
TypeError: unhashable type: 'list'

Convert Dictionary to Set

If you use the above technique to convert a Dictionary to Set, then it throws an error.

# Dictionary to Set
mySet1 = {'a':1, 'b':2, 'c':3}
print(mySet1)
print({mySet1})

Converting Dictionary to Set output

{'a': 1, 'b': 2, 'c': 3}
Traceback (most recent call last):
  File "/Users/suresh/Desktop/simple.py", line 4, in <module>
    print({mySet1})
TypeError: unhashable type: 'dict'

Insert items into Python Set

The following options are available to insert new items into the existing Set.

  1. add(x): Add one item to the existing set.
  2. update(): Add multiple items to the existing set.

Python set add Method

In this example, we use the add method to add an item to the existing set.

# Add Items to set 

mySet = {1, 2, 4, 5}
print("Old Set Items = ", mySet)

# Set add
mySet.add(3)
print("New Set Items = ", mySet)

FruitSet = {'apple', 'Mango', 'orange', 'cherry','kiwi'}
print("\nOld Set Items = ", FruitSet)

# Set add
FruitSet.add('banana')
print("New Set Items = ", FruitSet)

set add function output

Old Set Items = {1, 2, 4, 5}
New Set Items = {1, 2, 3, 4, 5}

Old Set Items = {'kiwi', 'orange', 'Mango', 'cherry', 'apple'}
New Set Items = {'kiwi', 'orange', 'banana', 'Mango', 'cherry', 'apple'}

Python set update Method

The set update method helps us to add multiple set items. Here, we add multiple set items. Remember, you use duplicate value inside the update method, the set ignores them.

# set update

mySet = {1, 2, 4, 5}
print("Old Set Items = ", mySet)

# Set update
mySet.update([2, 3, 6, 7])
print("New Set Items = ", mySet)

FruitSet = {'apple', 'Mango', 'orange','kiwi'}
print("\nOld Set Items = ", FruitSet)

# Set update
FruitSet.update({'banana', 'cherry'})
print("New Set Items = ", FruitSet)

set update function output

Old Set Items =  {1, 2, 4, 5}
New Set Items =  {1, 2, 3, 4, 5, 6, 7}

Old Set Items =  {'apple', 'Mango', 'kiwi', 'orange'}
New Set Items =  {'banana', 'kiwi', 'orange', 'apple', 'Mango', 'cherry'}

It is another example of the set update method.

# set update

mySet = {1, 2, 5, 6}
print("Old Set Items = ", mySet)

# Set update
mySet.update([2, 3, 6, 7], {5, 8, 9})
print("New Set Items = ", mySet)

Set update Function output

Old Set Items =  {1, 2, 5, 6}
New Set Items =  {1, 2, 3, 5, 6, 7, 8, 9}

Remove Set items

There are several different functions to delete or remove an item from a Set:

Python Set remove method

If we know the set item or the value inside the given set, use the remove method.

  • mySet.remove(4) removed 4 from mySet. After removing, the remaining set items adjusted themselves.
  • FruitSet.remove(‘orange’) removed orange from fruits set.
# set remove

mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print("Old Set Items = ", mySet)

# Set remove()
mySet.remove(4)
print("New Set Items = ", mySet)

FruitSet = {'apple', 'Mango', 'orange', 'banana', 'cherry','kiwi'}
print("\nOld Set Items = ", FruitSet)

# Set remove()
FruitSet.remove('orange')
print("New Set Items = ", FruitSet)
Python Set 9

Remove Python set item using del statement

The del statement completely removes the given set. If you select the set after executing this del method, it throws an error. It is because this set del function altogether removes the set.

# set del

mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print("Old Set Items = ", mySet)

# Set del
del mySet
print("New Set Items = ", mySet)
Python set Example 13

Remove set items using clear method

The set clear method helps to clear all the items in a given set. After executing this method, it returns an empty set = set().

# set clear

mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print("Old Set Items = ", mySet)

# Set clear()
mySet.clear()
print("New Set Items = ", mySet)

FruitSet = {'apple', 'Mango', 'orange', 'banana', 'cherry','kiwi'}
print("\nOld Set Items = ", FruitSet)

# Set clear()
FruitSet.clear()
print("New Set Items = ", FruitSet)

set clear method output

Old Set Items = {1, 2, 3, 4, 5, 6, 7, 8, 9}
New Set Items = set()

Old Set Items = {'cherry', 'kiwi', 'Mango', 'banana', 'apple', 'orange'}
New Set Items = set()

Remove Set item using discard method

The set discard method removes the set item. If we know the item or value that you want to delete then, use discard to remove the given set item.

In python, discard and remove functions are the same. However, if you try to remove a non-existing item, then set remove function with raise an error, and the set discard function won’t raise any error.

# Python set discard

mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print("Old Set Items = ", mySet)

# Set discard()
mySet.discard(7)
mySet.discard(4)
print("New Set Items = ", mySet)

FruitSet = {'apple', 'Mango', 'orange', 'banana', 'cherry','kiwi'}
print("\nOld Set Items = ", FruitSet)

# Set discard()
FruitSet.discard('Mango')
print("New Set Items = ", FruitSet)

The output of the above set discard example is

Old Set Items = {1, 2, 3, 4, 5, 6, 7, 8, 9}
New Set Items = {1, 2, 3, 5, 6, 8, 9}

Old Set Items = {'banana', 'cherry', 'orange', 'Mango', 'kiwi', 'apple'}
New Set Items = {'banana', 'cherry', 'orange', 'kiwi', 'apple'}

set discard Analysis

  • mySet.discard(7) removing 7 from mySet.
  • mySet.discard(4) removing 4 from mySet.
  • Next, we declared a fruit set contains 6 fruit names.
  • FruitSet.discard(‘Mango’) removing Mango from fruit set.

Remove set items using pop method

The set pop method removes the last item from a given set. As we all know, sets are not in any particular order. So, you never know which item removed from the set. Although it is not worth it, I am giving one set example. So, you get the idea.

# set discard

mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print("Old Set Items = ", mySet)

# Set discard()
mySet.discard(7)
mySet.discard(4)
print("New Set Items = ", mySet)

FruitSet = {'apple', 'Mango', 'orange', 'banana', 'cherry','kiwi'}
print("\nOld Set Items = ", FruitSet)

# Set discard()
FruitSet.discard('Mango')
print("New Set Items = ", FruitSet)

set pop function output

Old Set Items = {1, 2, 3, 4, 5, 6, 7, 8, 9}
New Set Items = {1, 2, 3, 5, 6, 8, 9}

Old Set Items = {'Mango', 'cherry', 'banana', 'apple', 'kiwi', 'orange'}
New Set Items = {'cherry', 'banana', 'apple', 'kiwi', 'orange'}