We Offer 100% Job Guarantee Courses (Any Degree / Diploma Candidates / Year GAP / Non-IT / Any Passed Outs). Placement Records
Hire Talent (HR):+91-9707 240 250

General

Python Sets

Python Sets

Python Sets

What is a set?

A set is an unordered collection of items in which every element is unique, iterable and immutable (cannot be modified). However, the set as a whole is mutable. There are no duplicate elements in a set and you can add or even delete items in it. Sets can be helps to perform mathematical operations like intersection ,union, symmetric difference and so on. A set can consist of elements or items with different immutable data types like integer, string, float, tuple, etc. However, a set cannot have mutable elements like lists, dictionaries or a set itself.

By the term “Set” you must have got an idea that it is something on “Grouping”. Yes, you got right!! Grouping elements into a set is one of the important things in python. Python has a few built in set type.Is this article, we will focus on understanding everything about the set in python; how to use to it. Here is a quick glance on what are things that we will be covering

What is a Set in Python?

When should you use Set?

How to create a set?

How to modify a set in python?

How to remove elements from a set?

Set operations

  • Finding the set length
  • Access the set
  • Removing the set
  • Union of set
  • Set Intersections
  • Difference of set

What does Frozen Set mean?

  • Creation of a frozen set
  • Accessing frozen set

Defining a set in Python

A set has a list of items that are enclosed within curly brackets and separated by commas. However, if you an older version of Python, you may have to use the set keyword. The set keyword works in the later versions of Python as well. The example below shows two sets (months and mixed_set) of defined elements with the same data type as well as with different data types respectively. The output shows a random order of the elements within the set. Thus, a set is an unordered collection of items.

A set is a data type, which is an unordered collection of elements. Every element in the set must be unique and must be immutable (unchangeable). These elements can be of the data type. However, sets are in itself data structure, which is unordered and mutable (changeable). These are used for performing mathematical operations such as union, intersection, etc.

Example:1

My_Print= {10, ‘z’, 7}

print (My_Print)

 Output:

{‘z’, 10, 7}

The output displays all the elements available in My_Print. A set as a whole can be changed, but the elements present in the set are unchangeable.

Example:2

months = {"Jan","Feb","Mar"}
days = set(["Mon","Tue","Wed"]) #using set keyword
mixed_set = {(1, 2, 3), "Good Morning", 32.0}
print(months)
print(days)
print(mixed_set)

Output

{'Feb', 'Mar', 'Jan'}
{'Tue', 'Mon', 'Wed'}
{32.0 , (1, 2, 3), "Good Morning"}

When should you use Set?

You can use set in python only when:

  • An order doesn’t matter
  • Repetition is not required
  • For mathematical operations

After this, let’s see how to create sets?

How to Create Sets?

You can create set either by placing all the items in the curly braces or by using the set () function. The elements can be of integer, string, float, etc).

Example1: Using curly braces

My_Print= {10, ‘Hi’, (7)}

print (My_Print)

Output:

10, ‘Hi’, (7)

Example2: Using Set () function

H= set ({10, 9.0, ‘bye’})

print (a)

Output:

({10, 9.0, ‘bye’})

Apart from this, you also have an empty set if you want.

Example 3: Empty set

Et=set()

print(Et)

Output:

set ()

How to modify a set in python?

If you want to add only one element, then use add () method, and for adding multiple-element you need to use the update() method.

Example1: For adding single element

m = {10,3}

print(m)

m.add(2)

print(m)

Output:

{10,3}

 {10,2, 3}

Example2: Using update() method

m = {10,3}

print(m)

m.update([2,3,4])

print(m)

Output:

{10,3}

{10,2,3,4}

How to remove elements from a set?

To remove particular elements you can use discard () and remove (). The main difference between both of them are discarded (), is for removing an item that does not exist. But remove () is for removing the element that exists.

Example1: Using remove() function

My_print={10, 20, 9.0, 78}

My_print.remove(20)

print(My_print)

Output:

{10, 9.0, 78}

If you are specifying an element that is not present in the set, then it will throw an error. However, if you want to remove about which you are unsure that it is present in the set or not, then you can use discard() function.

Example2: Using discard() function

My_print={10, 20, 4.6, 1.2, 'x', 'z'}

My_print.discard(4.6)

My_print.discard('i')

print(My_print)

Output:

 {10, 20, 1.2, ‘r’, ‘s’}

After knowing about adding, removing, modifying the element in a set. Let’s have a look at the set operations.

Accessing items in a set

A set element cannot be referenced by an index number since it is unordered. However, the items in a set can be looped through by using a for a loop. You can also choose to access a particular item in a set by using the “in” keyword. However, note that it is case sensitive.

Using for loop

fruits_set = {"mango", "banana", "orange"}
for x in fruits_set:
print(x)

Output

banana
cherry
apple

Using “in” keyword

fruits_set = {"mango", "banana", "orange"}
print("orange" in fruits_set)
print("Orange" in fruits_set)

Output

True

False

Click Here -> Get Python 100% Practical Training

Adding more items in a set

You can add more items in a set by using the add() method. Since a set does not use indexing, you need to specify the exact value within the method parenthesis.

Example

flower_set = {"tulip", "geranium", "orchid"}
flower_set.add("anthurium")
print(flower_set)

Output

{'tulip', 'orchid', 'geranium', 'anthurium'}

Removing items from a set

You can remove an item from a set by using the discard() method. Since there is no index attached to an item in a set, you would need to specifically address the value within the method parenthesis.

Example

flower_set = {"tulip", "geranium", "orchid"}
flower_set.discard("tulip")
print(flower_set)

Output

{'orchid', 'geranium'}

Clearing all items in a set

You can remove all items in a set by using the clear() method.

Example

flower_set = {"tulip", "geranium", "orchid"}
flower_set.clear()
print(flower_set)

Output

set()

Click Here-> Become a Python Certified Experts in 25 Hours 

Copying a set

Example

An existing set can be copied to a new set by using the copy() method.
flower_set = {"tulip", "geranium", "orchid"}
new_flower_set = flower_set.copy()
print("new set: ", new_flower_set) 

Output

new set:  {'orchid', 'tulip', 'geranium'}

Sorting a set

The values in a set can be sorted in ascending or descending order using the sorted() method. By passing the set variable inside the sorted()  parameter, the items in a set will be printed in ascending order by default. The sorted() method takes in three parameter-iterable, key and reverse. The iterable parameter is required in which you need to specify the variable name of the set. The key and reverse parameter is optional. You can use the reverse parameter to sort the items in ascending order (reverse = False) or descending order (reverse = True).

Example

vowel_set = {"e", "a", "u", "o", "i"}
print("Default sort: ", sorted(vowel_set))
print("Ascending order: ",sorted(vowel_set,reverse=False))
print("Descending order: ", sorted(vowel_set, reverse=True))

Output

Default sort:  ['a', 'e', 'i', 'o', 'u']
Ascending order:  ['a', 'e', 'i', 'o', 'u']
Descending order:  ['u', 'o', 'i', 'e', 'a']

Updating a set

You can update a set by adding elements from one set to another set. You can use the update() method to do this. In the example below, set A is updated by adding all the elements of set B in set A. Common elements between the two sets are updated as one element. In this case, both set A and set B have 1 as a common element so when set A is updated, it is not repeated.

Example

A = {'a', 'b', 1}
B = {1, 2, 3}
print('A =',A)
print('B =',B)
result = A.update(B)
print('Update A =',A)

Output

A = {'b', 'a', 1}
B = {1, 2, 3}
Update A = {1, 2, 'b', 3, 'a'}

Set Operations

The sets in python are for carrying out mathematical operations like union, intersection, etc. This is possible to do using the operators or methods

Union of sets

The union operation (Set1 | Set2) can be used to compare two sets and produce a new set that contains distinct elements from both the sets. For instance, if there are more than two occurrences of the same element in both the sets, the new set would produce the element only once so there would be no repetition of elements. In the example below, “Wed” can be found in both days1 and day2 so when using the union operation, it would produce “Wed” only once as shown in the output. You can either use the union operator | or union() method in this case. The union() method is similar to the update() method. However, by using the union() method, the results are produced in a new set rather than updating an existing set.

Union of A and B is a combination of all elements from both the sets and making it into a single set. The symbol is | for the union. This can be accomplished using the union () method.

Example1: Using | symbol

A = {1, 2, 3, 4, 5}

B = {4, 5, 6, 7, 8}

C= A|B

Print (A|B)

Output:

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

You can perform the same task using union() method.

Example2: Using union() method

x={10, 20, 4.6, 7, 8, 'a', 'b'}

y={2,5,'d','abc'}

print("Set x U y = ",x.union(y))

Output:

Set x U y = {10, 20, 4.6, 5, 7, 8, ‘a, ‘abc’, ‘b’,  ‘d’}

Example:3

days1 = {"Mon","Tue","Wed"}
days2 = {"Wed","Thu","Fri","Sat","Sun"}
days = days1|days2
print(days)
days = days1.union(days2)
print(days)

Output

{'Sat', 'Thu', 'Wed', 'Sun', 'Tue', 'Mon', 'Fri'}
{'Sat', 'Thu', 'Wed', 'Sun', 'Tue', 'Mon', 'Fri'}

Click Here-> Python Interview Questions and Answers

Intersection of sets

The intersection operation (Set1 & Set2) can be used to compare two sets in which only the common elements between the sets will be produced in a new set. In the following example, since “Wed” is common both sets, the new set “days” will return “Wed” as the output. You can either use the & operator or intersection() method in this case.

The intersection of sets with elements that is present in those sets. There are two ways to do this one is ‘&’ symbol and the other one is intersection() method

Example1: & Method

x={1, 0, 5, 2.0}

b={1,5,'abc'}

c={1,3,4,}

print(a&b)

print(a&b&c)

Output:

{1,5}

{1}

Example2: Intersection() function

a={1, 0,5, 2.0}

b={1,5,'d','abc'}

c={1,3,4}

print("Set a intersection b = ",a.intersection(b))

Output:

Set a intersection b= {1,5}

Example:3

days1 = {"Mon","Tue","Wed"}
days2 = {"Wed","Thu","Fri","Sat","Sun"}
commonDays1 = days1 & days2
print(commonDays1)
commonDays2 = days1.intersection(days2)
print(commonDays2)

Output

{'Wed'}
{'Wed'}

Updating the intersection of sets

While the intersection of two sets is produced in a new set by using intersection(), an intersection_update() method is used to update an existing set.

Example

days1 = {"Mon","Tue","Wed"}

days2 = {"Wed","Thu","Fri","Sat","Sun"}

day1 = days1.intersection_update(days2)

print(day1)

Output

{‘Wed’}

Difference of sets

The difference operation (Set1 – Set2) can be used to compare two sets where the elements found only in one set will be produced in a new set. This means that common elements found between two sets are not produced in the new set. You can either use the – operator or difference() method in this case.

If we look at the following example, ColorA – ColorB produces a set where the unique elements in Color A are produced. Likewise, ColorB – Color A produces a set where the unique elements of Color B are produced. Moreover, common elements are not added to any of the new sets, ColorAB and ColorBA.

This difference of sets is for producing a new set that consists of elements that are unique in those sets. This is possible in ‘-‘ symbol or using the difference() function

Example1: ‘-‘ symbol

a={10, 20,50, 4.6, 'x', 'y'}

b={20,50,'d'}

print(a-b)

Output:

{10, 4.6, ‘x’, ‘y’, ‘d’}

Example2: difference() function

x={10, 20,5,'r', 's'}

y={20,5,'d','abc'}

print("Set a - b = ",a.difference(b))

Output:

Set a - b = {10, ‘r’, ‘s’, ‘abc’}

Now, in some case, you might want to alter the elements of your set, then in that case, you can make use of frozen.

Example:3

ColorA = {"Red","Green","Blue","Yellow"}
ColorB = {"Orange","Pink","Purple","Green","Yellow"}
ColorsAB = ColorA - ColorB
ColorsBA = ColorB.difference(ColorA)
print("ColorA - ColorB: ", ColorsAB)
print("ColorB - ColorA: ", ColorsBA)

Output

ColorA - ColorB:  {'Blue', 'Red'}
ColorB - ColorA:  {'Purple', 'Orange', 'Pink'}

Updating the difference of sets

While the difference of two sets is produced in a new set by using the difference() method, difference_update() method is used to update the difference in an existing set. In the example below, ColorA is updated by keeping the unique elements that are unique to ColorA which is red and blue. It removes those elements that are common to another set in comparison (in this case, ColorB). Hence, since green and yellow are also found in ColorB, it is removed from ColorA.

Example

ColorA = {"Red","Green","Blue","Yellow"}
ColorB = {"Orange","Pink","Purple","Green","Yellow"}
print("Color A: ", ColorA)
print("Color B: ", ColorB)
ColorA.difference_update(ColorB)
print("Color A: ", ColorA)

Output

Color A:  {'Green', 'Yellow', 'Blue', 'Red'}
Color B:  {'Green', 'Pink', 'Orange', 'Purple', 'Yellow'}
Color A:  {'Red', 'Blue'}

Subsets and supersets

You can use the <= operator or issubset() method to check if a set is a subset of another set. If it is, it would return True else it would return False. Similarly, you can use the >= operator or issuperset() methodto check if a set is a superset of another set.

Example

Employees = {"Max","Teresa","Josh","Terrance","Beth" }
Helpdesk_Employees = {"Teresa", "Josh"}
Subset = Helpdesk_Employees <= Employees
Superset = Employees >= Helpdesk_Employees
print(Subset)
print(Superset)
Subset = Helpdesk_Employees.issubset(Employees)
Superset = Employees.issuperset(Helpdesk_Employees)
print(Subset)
print(Superset)

Output

True
True
True
True

Symmetric difference of sets

You can find the unique elements between two sets by using the symmetric_difference() method. In the example below, the output elements are all unique and cannot be found in another set.

Example

set_A = {1, 2, 3, 4, 5}
set_B = {6, 7, 8, 1, 2}
print(set_A.symmetric_difference(set_B))
print(set_B.symmetric_difference(set_A))

Output

{3, 4, 5, 6, 7, 8}

{3, 4, 5, 6, 7, 8}

Updating symmetric difference of sets

An existing set is updated by storing all the elements that are unique between the existing set and the set which is being compared (set_B in this case).

Example

set_A = {1, 2, 3, 4, 5}
set_B = {6, 7, 8, 1, 2}
print(set_A.symmetric_difference_update(set_B))
print(set_A)

Output

{3, 4, 5, 6, 7, 8}

What is Frozen Set?

Frozen is immutable in python. Here, you cannot modify the values, which is immutable. It is a key-value pairs. But like sets, it is will not be ordered. Like normal sets, you can perform different operations like union, intersection, etc.

The syntax of Frozen is frozenset:

frozenset([iterable])

Note:

  • The frozenset() method can take only a single parameter.
  • The iterable is optional. The iterable contains elements for initializing the frozen set.
  • The frozen set are immutable and you cannot perform operations such as add(), remove(), update(), etc.

Example:

h={1,2, 10, 4.6, 7.8, ‘x’, ‘y’}

b=frozenset(h)

print(b)

Output:

frozenset({1, 2,10,  4.6, 5, 7.8, ‘x’, ‘y’})

How to Create Frozen Sets?

You can access the elements of the frozen set using the loops. Go through the below example and know how to do that.

Example:

b=frozenset([‘a’, ‘e’, ‘I’, ‘o’, ’u’, 'x', 'y'])

for z in b:

print(z)

Output:

a

e

i

o

u

x

y

This output shows that using the ’for’ loop, all the elements of the frozen set will be displayed one after the other. We assume that you might be clear with all the things that we have discussed in our tutorial. By this, the set on python ends. Have any doubts or require any clarification? If yes, we would request you to contact our support team and get your doubts clarified.

Click Here-> Get Python Training with Real-time Projects

Besant Technologies WhatsApp