Sets in Python | Python Sets and Operations performs on them

Sets-in-python
  • Save

Table of Contents

Sets in Python

  1. Sets in Python is an unordered collection of items.
  2. The elements of Sets in Python are unique (no duplicates), iterable, and must be immutable (cannot be unchanged).
  3. Sets in Python are mutable which means we can add or remove items from the Sets.
  4. Sets in Python are represented by curly braces {}.
  5. In Sets, there is no concept of the index which means there is no index attached to the elements of the Sets.
  6. Sets in Python are totally based on a data structure known as a hash table.

Advantages of Using Sets in Python

  1. As compared to List, Sets in Python is a highly optimized method for checking whether the element is present or not in the collection.
  2. It can be used to store unique values in order to remove duplicate elements from the collection.

Creating a Set in Python

Sets in Python can be created by placing any number of items inside the curly braces {} and separating the items by using commas between the items. The items in the sets are immutable. The items can be of the same datatype or a different datatype than what we can store in the set.

"""Creating a sets in Python"""


1) user_name = {"Morris", "Kale", "Andrew", "Tate", "Kale"}
print(user_name)


#Output:
{'Andrew', 'Morris', 'Kale', 'Tate'}


2) random_info = {1, "Alex", (1, 4, 3, 2), 2}
print(random_info)


#Output:
{1, (1, 4, 3, 2), 2, 'Alex'}

Above example 1, shows that the Sets contain the items of the same datatype, but you can clearly see that set contains duplicate items of Kale while assigning the value of user_name.

But in the output, there is only one item of Kale, which means it removes the duplicate items.

Example 2, shows that the Sets contain the items of the different data types, you can clearly see that the

set contains duplicate items of Alex while assigning the value of random_info.

But in the output, there is only one item for Alex, which means it removes the duplicate items.

Creating Set in Python using the set() method

You can easily create or typecast another datatype to set by using the set method.

"""Using the set method"""


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


print(demo_set)


#Output:
{1, 2, 3, 4, 5}


2) print(type(demo_set))


#Output:
<class 'set'>

The above example 1, shows that taking the list and converting the list datatype to set datatype.

You can check that in the list there is a duplicate element, i.e.,  4, while in the set there are no duplicate elements.

The above example 2, shows the type of the demo_set, which is the Set datatype in Python.

Note:

Sets in Python can contain any type of element, like floats, integers, tuples, etc. But mutable elements like dictionaries, lists, and sets can’t be members of sets in Python.

1) demo_set = set([1, 2, 3, 4, 5, 4])
print(type(demo_set))


#Output
<class 'set'>


2) set1 = {"Alex", "Sam", 3, ["BinFin", 4]}
print(type(set1))


#Output:
Traceback (most recent call last):
  File "Sets.py", line 26, in <module>
    set1 = {"Alex", "Sam", 3, ["BinFin", 4]}
TypeError: unhashable type: 'list'

Above Example 1, you can see that the Set contains the element of an integer datatype, so when I want to see the data type of that variable, it returns the Set.

In example 2, you can see that there is an element of the List datatype that is not allowed in the set. Therefore, it does not return the type of set; instead, it returns the error.

Empty Curly braces Difference in Python

1) name = {}


print(name)
#Output:
{}


print(type(name))
#Output:
<class 'dict'>


2) employee_info = set()


print(employee_info)
#Output:
set()


print(type(employee_info))
#Output:
<class 'set'>

In example 1, we have only assigned the curly braces to the name variable. When we print the type of name variable it returns the dictionary datatype.

In example 2, we have only assigned the value of the set function to the employee_info variable. When we print the type of employee_info, it returns the Set datatype.

Conclusion:

  1. When we assign only curly braces it means that it is a Dictionary datatype.

When we assign a set() the value it means that is a Set datatype.

Operations performed on Sets in Python

A) Adding elements to Sets in Python

Sets are mutable, and they are also unordered, so there is no concept of indexing.

So there are two methods for adding or updating the elements in the sets, i.e., add() and update(). We can add a single element to the set by using add(). We can add multiple elements to the set by using the update() function.

weeks = {"Sunday", "Monday", "Tuesday"}


print("Before adding :", weeks)


#Output:
Before adding : {'Monday', 'Tuesday', 'Sunday'}


weeks.add("Wednesday")
weeks.add("Thursday")


print("After adding :", weeks)


#Output:
After adding : {'Thursday', 'Tuesday', 'Sunday', 'Wednesday', 'Monday'}

As you can see in the above example, before adding, there were only three elements in the set, while after using add() twice, there were five elements in the set.

months = {"January", "February", "March"}


print("Before updating the set:", months)


#Output:
Before updating the set: {'January', 'February', 'March'}


months.update(["April", "May", "June"])
months.update(["July", "August"])


print("After updating the set:", months)


#Output:
After updating the set: {'August', 'February', 
'January', 'May', 'April', 'July', 'June', 'March'}

As you can see in the above example, before adding or updating, there were only three elements in the set, while after using update() twice, there were eight elements in the set. In the first update(), taking multiple elements as a list but at the time of update, it converts as Set’s element.

B) Remove items of Sets in Python

To remove the items from the sets, Python provides two functions, i.e., remove() and discard(). Both functions are used to remove the elements from the set. The only difference is that with remove() if the element is not present in the set, it will throw an error, while with discard() if the element is not present, it does not throw an error

## Using the remove function
weeks = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"}


1) print("Before removing:", weeks)


#Output:
Before removing: {'Tuesday', 'Sunday', 'Thursday', 
'Wednesday', 'Monday'}


2) weeks.remove("Monday")
print("After removing:", weeks)


#Output:
After removing: {'Tuesday', 'Sunday', 'Thursday', 'Wednesday'}


3) weeks.remove("Friday")




#Output:
Traceback (most recent call last):
  File "Sets.py", line 70, in <module>
    weeks.remove("Friday")
KeyError: 'Friday'

In example 1, the program prints all the elements in the set, while after using the remove method in example 2, it removes the element of Monday. But in example 3, we are trying to remove the element that is not present in the set, so that’s why we are getting a key error.

## Using the discard function


weeks = {"Sunday", "Monday", "Tuesday", 
"Wednesday", "Thursday"}


1) print("Before removing:", weeks)


#Output:
Before removing: {'Sunday', 'Wednesday', 'Thursday', 
'Tuesday', 'Monday'}


2) weeks.discard("Monday")


print("After removing:", weeks)


#Output:
After removing: {'Sunday', 'Wednesday', 'Thursday', 'Tuesday'}


3) weeks.discard("Friday")


print(weeks)
#Output:
{'Sunday', 'Wednesday', 'Thursday', 'Tuesday'}

In example 1, the program prints all the elements in the set, while after using the discard method in example 2, it removes the element of Monday. But in example 3, we are trying to discard the element that is not present in the set; it maintains the program flow, while in the remove method, it throws a key error.

Note:

There are other two methods by which we can delete the elements of the set that are not based on the key.

i.e., pop() and clear().

The pop() method removes the last element of the set.

The clear() method removes all the elements from the set.

weeks = {"Sunday", "Monday", "Tuesday", 
"Wednesday", "Thursday"}


1) print("Before removing:", weeks)


#Output:
Before removing: {'Wednesday', 'Sunday', 'Thursday', 
'Monday', 'Tuesday'}


2) weeks.pop()
weeks.pop()


print("After removing:", weeks)


#Output:
After removing: {'Thursday', 'Monday', 'Tuesday'}


3) weeks.clear()


print("After using the clear method:", weeks)


#Output:
After using the clear method: set()

In example 1, the program prints all the elements in the set, while after using the pop method twice in example 2, it removes the last two elements from the set. But in example 3, we are using a clear method, which is used to remove all the elements from the set. As we can see in the example 3 output, it is only left with the empty set.

Mathematical Operation performed on Sets in Python

A) Union of Sets

The union of two sets is performed by using the pipe (|) operator. The union of two sets means that it contains the elements of both sets and removes the duplicate items.

A union of two sets can be done by using the union() method, which is provided by Python.

#Using pipe operator


week1 = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"}


week2 = {"Friday", "Saturday"}


print(week1 | week2)


## Output:
{'Thursday', 'Friday', 'Tuesday', 'Saturday', 
'Monday', 'Wednesday', 'Sunday'}


# Using union function


print(week1.union(week2))


#Output:
{'Thursday', 'Friday', 'Tuesday', 'Saturday', 
'Monday', 'Wednesday', 'Sunday'}

B) Intersection of Sets

The intersection of sets means that it will return the common elements of both sets.

It can be performed by using the ampersand (&) operator.

It can be done by using the intersection function, which is provided by Python.

week1 = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"}


week2 = {"Friday", "Saturday", "Tuesday", "Sunday"}


print(week1 & week2)
#Output:
{'Sunday', 'Tuesday'}


print(week1.intersection(week2))
#Output:
{'Sunday', 'Tuesday'}

C) Sets of Difference

The difference between two sets can be calculated by using the subtraction operator (-). Suppose there are two sets A and B, and the difference is A-B that denotes the resulting set will be obtained that the element of A, which is not present in B.

Differences between the two sets can be done by using the difference() method which is provided by Python.

week1 = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"}


week2 = {"Friday", "Saturday", "Tuesday", "Sunday"}


print(week1 - week2)


#Output:
{'Thursday', 'Wednesday', 'Monday'}


print(week1.difference(week2))


#Output:
{'Thursday', 'Wednesday', 'Monday'}

D) Symmetric Difference of Sets:

The symmetric difference of the sets can be performed by using the wedge operator (^). Symmetric difference of sets means that it removes that element that is present in both sets.

The symmetric difference can also be performed by using symmetric_difference(), which is provided by Python.

week1 = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"}


week2 = {"Friday", "Saturday", "Tuesday", "Sunday"}


print(week1 ^ week2)
#Output:
{'Saturday', 'Monday', 'Friday', 'Thursday', 'Wednesday'}


print(week1.symmetric_difference(week2))
#Output:
{'Saturday', 'Monday', 'Friday', 'Thursday', 'Wednesday'}

Note: The symmetric difference of sets can be called the reciprocal of the intersection of sets.

Frozen Sets in Python

In simple terms, “frozen set” means that the items of the set cannot be changed, and therefore it can be used as a key in the dictionary.

The elements of the frozen set cannot be changed after the creation, which means we cannot add to or change the items of the frozen set. We can only read the content of the Frozen set.

frozenset() is used to create the frozen set object. The iterable sequence is passed into this method, which is converted into the frozen set as a return type of the method.

# Frozen set
week = frozenset(["Sunday", "Monday", "Tuesday"])


print(week)


#output:
frozenset({'Tuesday', 'Monday', 'Sunday'})


print(type(week))
#Output:
<class 'frozenset'>

Difference between a List and Set in Python

List in PythonSet in Python
The list in Python is an ordered sequence.The set in Python is an unordered sequence.
The elements in the list sequence can be changed or replaced.The elements in the set sequence cannot be changed or replaced.
The list in Python is mutable.The set in Python is mutable, but only stores immutable elements
Difference between Set and List in Python

FAQ

What are sets in Python?

Sets in Python are an unordered collection of items.

The elements of sets in Python are unique (no duplicates), iterable, and must be immutable (cannot be unchanged).
Sets in Python are mutable, which means we can add or remove items from the sets.

Sets in Python are represented by curly braces {}.

Is {} a set in Python?

Sets in Python can be created by placing any number of items inside the curly braces {} by separating the items by using commas between the items.

Why use a set in Python?

As compared to lists, sets in Python are a highly optimized method for checking whether an element is present or not in the collection.

It can be used to store unique values in order to remove duplicate elements from the collection.

What is the difference between a list and a set in Python?

The list in Python is an ordered sequence.
The set in Python is an unordered sequence.

The elements in the list sequence can be changed or replaced.
The elements in the set sequence cannot be changed or replaced.

Write blogs related to Ethical hacking, Computer networks, Linux, Penetration testing and Web3 Security.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top
0 Shares
Share via
Copy link