Python Set

A Python set data type is similar to Lists. However, it does not accept duplicate items (unique values). It is an unordered collection of zero or more items that are unindexed (no index position).

Python set allows mutable items, so adding and removing items is very easy. However, slicing is not possible because of no index. Generally, sets are very useful for performing mathematical operations like unions, Intersections, comparisons, and differences.

Python set Declaration

It can be created by placing the required items inside curly braces or using the set() function without any arguments. It allows you to place different kinds of data type items like integer, string, etc., in a single one. The following is the available list of ways to declare them.

# Declaration

# Empty
s1 = {}
s2 = set()

# With Integer Keys
s3 = {1, 2, 3, 4, 5}

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

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

# Using ()
s7 = set([1, 2, 3, 4, 5])
s8 = set((1, 2, 3, 4, 5, 6, 7))

# Example 2
s9 = (['apple', 'kiwi', 'banana', 'orange'])
s10 = (('apple', 'kiwi', 'banana', 'orange'))

Python set Example

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

# Declaration

# Empty 
s1 = {}
s2 = set()

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

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

print(s1)
print(s2)
print(s3)
print(s4)
{}
set()
{1, 2, 3, 4, 5}
{'apple', 'kiwi', 'orange', 'banana'}

Python Mixed Sets Example

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

# Mixed Data Types
myS1 = {1, 2, 1.5, 2.5, 'apple'}
myS2 = {'banana', 1, 2, (1, 2, 3)}

print(myS1)
print(myS2)

myS3 = set([1, 2, 3, 4, 5])

print(myS3)

myS5 = (['apple', 'kiwi', 'banana', 'orange'])
myS6 = (('apple', 'kiwi', 'banana', 'orange'))

print(mySet5)
print(mySet6)
{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')

{} vs set()

This Python example shows the difference between {} and set() while declaring them.

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

print(mySet)
print(mySet1)

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

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

How to Convert List to Set in Python?

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

mySet = [1, 2, 3]

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

How to convert Dictionary to Set in Python?

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

mySet1 = {'a':1, 'b':2, 'c':3}

print(mySet1)
print({mySet1})
{'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'

How to Insert items into the Python set using add & update?

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

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

The update method helps us to add multiple elements. Here, we add multiple items. Remember, if you use duplicate values inside the update method, python ignores them.

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

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

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

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

FruitSet.update({'banana', 'cherry'})
print("New Items = ", FruitSet)
Old Items =  {1, 2, 4, 5}
New Items =  {1, 2, 3, 4, 5, 6, 7}
New Items =  {1, 2, 3, 5, 6, 7, 8, 9}

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

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

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

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