< Prev
Next >

# Python - Set

In our previous Python article, we have explained a collection data types like tuple and list. Moving on in this tutorial, we are going to explain another collection data type provided by Python - set.

Unlike the tuple and list data type, the set data type is an unordered sequence of items i.e. the order in which items of a set are declared in a set is not the order in which they are stored because the objects are stored on the basis of their hash value, which is calculated internally.

• ## Important properties of a Set

• A set is mutable even i.e. we can insert a new item to it and can delete an existing item from it.
• We cannot store duplicate values in a set.
• Because the order in which items of a set are stored is arbitrary, so there is no concept of accessing an item of a set using an index position.

• ## Methods of the Set collection data type

• Now let us discuss important methods of set collection data type.

Methods Description
discard() Removes an item from the set.
clear() Clears/removes all the items in a set.
remove(item) Removes an item from the set, if unsuccessful raises KeyError.
pop() Removes an arbitrary item from the set, if unsuccessful raises KeyError.
copy() Returns copy of a set.
update(s) Adds all of the items in set s to the invoked set.
union(s) Returns a new set which has items of the invoked set and the set s.
intersection(s) Returns a new set which has common items in both the invoked set and the set s.
symmetric_difference(s) Returns a new set which has unique items in both the invoked set and the set s.
difference(s) Returns a new set which has items only in the invoked set and not in the set s.
union_update(s) Updates the invoked set and adds the items of the set s to it.
intersection_update(s) Updates the invoked set to contain only the items common in it and in the set s.
symmetric_difference_update(s) Updates the invoked set to contain only the unique items in it and in the set s.
difference_update(s) Updates the invoked set to contain the items which are not in the set s.

• ## How to create a set in Python?

• In order to create a set with items, we must declare its items within a pair of curly braces { }, where each item is separated by the comma, operator. Let us show you a simple example of how to create a set with items.

``````#Python - Creating a set with items

set_ex ={'Never give up', 19.2, -29, 'A'}
print(set_ex)``````

## Output

``{19.2, 'A', 'Never give up', -29}``

In the example above, we have created a set named set_ex, containing 4 items separated by the comma, operator and all items are enclosed within a pair of curly braces { }. Look carefully, the items of set are displayed in an arbitrary order, unlike the order in which they were declared within a set.

• ## Creating a set by calling the set() function

• Another way to create a set of items is by calling the built-in set() function. This function can be passed from zero to one argument, such as -
• If this function is passed zero arguments(no argument), it returns an empty set.
• If this function is passed a set, list or a dictionary as an argument, it converts it into a set and returns it.
• With any other kind of object as its argument, it tries to convert it to a set and returns it.

``````#Python - Creating a set with items using set() function

# Creating an empty set by calling set() with no argument.
set_ex = set()

# Printing the first set
print('First set : ', set_ex)

# Creating a set by calling set() with a set as its argument
set_ex2 = set({'Never give up', 19.2, -29, 'A'})

# Printing the third set
print('Second set : ', set_ex2)

# Creating a set by calling set() with a tuple as its argument
set_ex3 = set(('Never give up', 19.2, -29, 'A'))

# Printing the third set
print('Third set : ', set_ex3)

# Creating a dictionary
dict1 = {
4:'Fourth',
3:'Third',
'two':'Second',
'one':'First',
5:'Fifth'
}

# Creating a set by calling set() with a dictionary as its argument i.e. keys of a dictionary will be added to set
set_ex4 = set(dict1)

# Printing the fourth set
print('Fourth set : ', set_ex4)
``````

## Output

``````First set :  set()
Second set :  {'Never give up', 'A', 19.2, -29}
Third set :  {'Never give up', 'A', 19.2, -29}
Fourth set :  {'two', 3, 4, 5, 'one'}``````

• ## Iterating over items in a set by using the for loop

• We can iterate over the items in a set by using the membership operator in with the for loop. Let us see how we do this.

``````#Python - Iterating over items in a set

# Creating a set with items
set_ex ={'Never give up', 19.2, -29, 'A'}

# Using for loop to iterate over items in a set
for val in set_ex:
print(val)``````

## Output

``````A
Never give up
19.2
-29``````

As you can see in the output, items are stored in an arbitrary order as compared to the order of their declaration.

• ## Mathematical operations supported by Set

• We can perform the union, intersection, difference and symmetric difference operations on a set of items using the associated operators explained in the table below.

Operations Description
Union Performs addition of two sets, using | operator and returns a new set.
Intersection Gives the common items in two sets, using & operator and returns a new set.
Difference Gives us the items present in one set but not in another, using - operator and returns a new set.
Symmetric Difference Gives us unique items present in two sets, using ^ operator and returns a new set.

``````#Python - Set Operations Example

# First set
set1 ={'Never give up', 10, -29, 'A', 1}

# Second set
set2 ={1, 20, 10}

print('First set : ', set1)
print('Second set : ', set2)

# Union of two sets using | operator i.e. adding items of two sets
print('Union of two sets : ', set1 | set2)

# Intersection of two sets using & operator i.e. items similar in two sets
print('Intersection of two sets : ', set1 & set2)

# Difference of two sets using - operator i.e. items in first set but not in second set
print('Difference between first and second set : ', set1 - set2)

# Symmetric difference of two sets using ^ operator i.e. unique items in both the first and second set
print('Symmetric difference between two sets : ', set1 ^ set2)``````

## Output

``````First set :  {1, -29, 10, 'A', 'Never give up'}
Second set :  {1, 10, 20}
Union of two sets :  {1, -29, 20, 'Never give up', 10, 'A'}
Intersection of two sets :  {1, 10}
Difference between first and second set :  {'Never give up', -29, 'A'}
Symmetric difference between two sets :  {-29, 20, 'Never give up', 'A'}``````

• ## Calling methods to perform mathematical operations

• Apart from using the operators discussed in our last example, we can also perform union, intersection, difference and symmetric difference operations on a set by using its methods - union(), intersection(), difference(), symmetric_difference().

Note : These methods will not modify the invoked set but will return a new set, reflecting the result of operations performed.

``````#Python - Set Operations Example

# First set
set1 ={'Never give up', 10, -29, 'A', 1}

# Second set
set2 ={1, 20, 10}

print('First set : ', set1)
print('Second set : ', set2)

# Union of two sets using union() method
print('Union of two sets : ', set1.union(set2))

# Intersection of two sets using intersection() method i.e. items similar in two sets
print('Intersection of two sets : ', set1.intersection(set2))

# Difference of two sets using difference() method i.e. items in first set but not in second set
print('Difference between first and second set : ', set1.difference(set2))

# Symmetric difference of two sets using symmetric_difference() method i.e. unique items in both the first and second set
print('Symmetric difference between two sets : ', set1.symmetric_difference(set2))``````

## Output

``````First set :  {1, 'Never give up', -29, 10, 'A'}
Second set :  {1, 10, 20}
Union of two sets :  {1, 'A', 'Never give up', -29, 20, 10}
Intersection of two sets :  {1, 10}
Difference between first and second set :  {'A', 'Never give up', -29}
Symmetric difference between two sets :  {'Never give up', -29, 'A', 20}``````

Note : If you want to modify the invoked set with the result of operations performed then you should call update methods, such as - union_update(), intersection_update(), difference_update(), symmetric_difference_update().

• ## A set is mutable

• Once we have declared a set with its items, it is mutable i.e. we can add new items to it by using the add(), and we can remove items from it by using the remove() or the discard() method of the set data type.

Note : We cannot store duplicate items in a set. Calling add() method to add a duplicate item in a set will not raise any error but the duplicate value will not be stored.

``````#Python - Iterating over items in a set

# Creating a set with items
set_ex ={'Never give up', 19.2, -29, 'A'}
print('Original set : ', set_ex)

print('Adding 2019 to set : ', set_ex)

# Calling add() method to add an existing item to a set
print('Adding -29 to set : ', set_ex)

# Calling remove() method to remove an existing item from a set
set_ex.remove(19.2)
print('Removing 19.2 from set : ', set_ex)

# Calling discard() method to discard an existing item from a set

print('Discarding -29 from set : ', set_ex)``````

## Output

``````Original set :  {19.2, 'Never give up', 'A', -29}
Adding 2019 to set :  {-29, '2019', 'A', 19.2, 'Never give up'}
Removing 19.2 from set :  {-29, '2019', 'A', 'Never give up'}
Discarding -29 from set :  {'2019', 'A', 'Never give up'}``````

• ## discard() v/s and remove() method

• Though both the methods discard() and remove() are used to remove a specific item from a set but there is a slight difference between these methods.

When the discard() method is called with an item that does not exist in a set, it leaves the set unaffected and doesn't return any error, in contrast, the remove() method throws an error i.e. KeyError when called with a not existing item in a set.

``````#Python - Difference between discard() and remove() method of set

# Creating a set with items
set_ex ={'Never give up', 19.2, -29, 'A'}
print('Original set : ', set_ex)

# Calling discard() method to discard a not existing item from a set
print('Discarding 0 from set : ', set_ex)

# Calling remove() method to remove a not existing item from a set returns an KeyError
set_ex.remove(10)

print(set_ex)``````

## Output

``````Original set :  {19.2, 'A', 'Never give up', -29}
Discarding 0 from set :  {19.2, 'A', 'Never give up', -29}
Traceback (most recent call last):
File "D:/Python/Python37/set3.py", line 15, in
set_ex.remove(10)
KeyError: 10``````

• ## Using the pop() method to remove a random item from a set

• Though the methods discard() and remove() are used to remove a specific item from a set, we could even use the pop method of the set collection data type, which removes a random item from a set. If the pop method is called on an empty list, it returns an error i.e KeyError. Let us see an example.

``````#Python - Using pop() method to remove a random item from set

# Creating a set with three items
set_ex ={'Never give up', -29, 'A'}
print('Original set : ', set_ex)

# Calling pop() removes a random element
set_ex.pop()
print('Modified set after calling pop() : ', set_ex)

# Calling pop() removes a random element
set_ex.pop()
print('Modified set after calling pop() : ', set_ex)

# Calling pop() removes a random element and the set will be empty now
set_ex.pop()
print('Modified set after calling pop() : ', set_ex)

# Calling pop() method on an empty set will return an error i.e. KeyError
set_ex.pop()
print('Modified set after calling pop() : ', set_ex)``````

## Output

``````Original set :  {'Never give up', -29, 'A'}
Modified set after calling pop() :  {-29, 'A'}
Modified set after calling pop() :  {'A'}
Modified set after calling pop() :  set()
Traceback (most recent call last):
File "D:/Python/Python37/set4.py", line 25, in
set_ex.pop()
KeyError: 'pop from an empty set'``````

• ## FrozenSet collection data type

• So far, we have studied the properties of the set collection data type, which is mutable. Python also provides a variant of set known as the frozen set collection data type which has almost all the properties of a set but unlike set data type, the frozen set is immutable, hence the frozen set data type does not have methods to allow us to add new items or delete existing items from it.

We could create a frozen set by calling the frozenset() function. Let us see an example

``````#Python - Frozenset example

# Creating a frozen set by calling frozenset() function
frozen_set_ex = frozenset({'Never give up', -29, 'A'})

# Printing items of a frozenset
print(frozen_set_ex)``````

## Output

``frozenset({'Never give up', 'A', -29})``

• ## Some important built-in functions to work with set

• Functions Description
max() Returns the maximum value in a set.
min() Returns the minimum value in a set.
len() Returs the total length of a set.
sum() Returns sum of all items in a set.
sorted() Returns a sorted copy of a set.
any() Returns true if any element in a set is true, else false.
all() Returns true if all elements in a set are true, else false.

``````#Python - Functions working with sets

#First set
set1 ={19, -20, 209, 799.99, -15.4}

#Second set
set2 =(1, True, False, 0) # 1 is boolean true, 0  for boolean false
# True(with capital T) is boolean true, False(with capital F) is boolean false

#Printing sets
print('Set1 : ', set1)
print('Set2 : ', set2)

#Using max() function with a set.
print('Maximum value in set1 : ', max(set1))

#Using min() function with a set.
print('Minimum value in set1 : ', min(set1))

#Using sum() function with a set.
print('Sum of values in set1 : ', sum(set1))

#Using sorted() function with a set.
print('Sorted copy of set1 : ', sorted(set1))

#Using all() function with a set.
print('all() boolean true values in set2 : ', all(set2))

#Using any() function with a set.
print('any boolean true value in set2 : ', any(set2))``````

## Output

``````Set1 :  {-20, 209, -15.4, 19, 799.99}
Set2 :  (1, True, False, 0)
Maximum value in set1 :  799.99
Minimum value in set1 :  -20
Sum of values in set1 :  992.59
Sorted copy of set1 :  [-20, -15.4, 19, 209, 799.99]
all() boolean true values in set2 :  False
any boolean true value in set2 :  True``````   