Python Set

Among the four sequences in Python is an important ability to collect unordered data. You might have come across the word set in your mathematical adventure at a point in school, and you’re familiar with the definition that sets are the collection of clearly defined objects or things. Now that knowledge will be needed in this lesson.

The purpose of this page is to teach you the following:

  • What is a Python Set?
  • Types of python set
  • Characteristics of the Python Set
  • How to create a Python set
  • How to modify
  • Deleting elements in Python set
  • Built-in python set methods

Then off you go to practice some set as I conclude

What is a Python Set?

The python set is the unordered collection of comma-separated data enclosed in curly brackets {}. A set is mutable but its items must be immutable. Sets are used to store multiple data in variables, it enables you to carry out similar operations on different items at once. Conclusively, because sets are unordered data it has no business with indexing. It’s worth noting that set is among the four frequently used data types in Python; others are List, tuple, and dictionary. However, there are two types of sets in Python which are:

  • The set
  • The Frozen set

We’ll be discussing them on this page.

So, what’s unique about the Python sets? That lands us at the next thought

Characteristics of the Python Set

All the data types in Python have unique Features that enable a distinct performance and the set is Known for:

  • Sets are unordered. This means that any item can come before any.
  • Set doesn’t allow repeated elements.
  • A set can be mutable but its items must be immutable
  • Set can contain any type of elements like float, string, integers, and tuple

With that being said, we must look at some examples in regards to the above characters. However, for all protocols observed, we have to create a set before further progress.

How To Create a Python Set?

It’s not difficult to create a set. A set can be created by enclosing an unclose item on curly brackets {}. You can as well execute. some sets using the set() function.

Example 1: Using Curly brackets to create sets

Python Unit:

months = {"January", "February", "march", "April", "May", "July", "August"}   
print(months)   
print(type(months))   
print("looping through the set elements ... ")   
for i in months:   
    print(i)  

Output:

{'January', 'February', 'March', 'April', 'May', 'June', 'July'}
<class 'set'>
looping through the set elements ...
May
February
January
June
April
July
March

Example.2: Creating a set using the set() function

Python Input

months = (["January", "February", "march", "April", "May", "July", "August"])  
print(months)   
print(type(months))   
print("looping through the set elements ... ")   
for I in months:   
    print(i)

Output:

{'January', 'February', 'March', 'April', 'May', 'June', 'July'}
<class 'set'>
looping through the set elements ...
May
February
January
June
April
July
March

Note. that the outputs aren’t ordered in the monthly sequence. That proves that sets are unordered

Now that we’ve created a set, it’s time we take off to some important operation on the python set

How To Modify Python Set?

This example agrees with the fact that the set itself can be modified but its elements are immutable.

Interestingly, Python enables you to modify sets in two methods which are:

  • add() function. It adds a single element to the set
  • update () function. To add multiple items in the set

Example 3: the add() and update() function

Python Input:

# initialize my_set
my_set = {January, March}
print(my_set)
# my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing
# add an element
# Output: {January, February, March}
my_set.add(February)
print(my_set)
# add multiple elements
# Output: {January, February, March, April}
my_set.update([February, March, April])
print(my_set)
# add list and set
# Output: {January, February, March, April, Mat, June, August}
my_set.update([April, May], {January, June, August})
print(my_set)

Output:

{January, March}
{January, February, March}
{January, February, March, April}
{January, February, March, April, May, June, August}

Deleting Elements in Python Set

There are two ways to delete an isolated item in a Python set. They are:

  • discard () function
  • remove () function

Example 4: to display the discard () and the remove() delete function.

Python Input

# Difference between discard() and remove()
# initialize my_set
my_set = {January, March, April, May, june}
print(my_set)
# discard an element
# Output: {January, march, May, june}
my_set.discard(april)
print(my_set)
# remove an element
# Output: {January, march, May}
my_set.remove(june)
print(my_set)
# discard an element
# not present in my_set
# Output: {january, march, May}
my_set.discard(February)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
my_set.remove(February)

Output:

{January, March, April, May, June}
{January, March, May, June}
{January, March, May}
{January, March, May}
Traceback (most recent call last):
  File "<string>", line 28, in <module>
KeyError: 2

I want you to note that:

  • discard() function won’t do any changes to the set of the elements (February is present in the set.
  • The remove() will return an error if the item(February) isn’t present in the list.

Before we progress with the basic operations on the Python set, let’s be clear on The two types of sets in Python:

Set

This is the context of the content you’re reading which you’ve gotten some extent of knowledge on. So said, let’s take off with its contrast

Frozen set

The frozen set is another type of set in Python that is immutable and it can be used as a key in the python dictionary. A frozen set is a contrast to the normal set that’s not frequently used. Although, it’s important and won’t be neglected.

The frozen set () function is used to create the frozen set data.

Example:

Python Input:

Frozenset = frozenset([January, February, March, April, May])    
print(type(Frozenset))   
print("\nprinting the content of frozen set...")   
for me in Frozenset:   
    print(i);   
frozenset. add(June) #gives an error since we cannot change the content of Frozenset after creation

Output:

<class 'frozenset'>
printing the content of the frozen set...
January
February
March
April
May

Traceback (most recent call last):

  File "set.py", line June, in <module>
    frozenset. add(6) #gives an error since we can change the content of Frozenset after creation
AttributeError: 'frozenset' object has no attribute 'add'

Operations On Python Set

The table below contains the basic operator’s inset

OperatorDescription
(|) Union setJoins all the elections in both sets print(1|2)={1, 2}
& IntersectionGives out the elements present in both sets {a,b}&{a,c}= {a}
– differenceCollects elements of one set that are not present in the other {1, 2, 4, 7} – {1, 4,,8} = {2, 7, 8}

 Built-in Python Set  Methods

Python enables the following methods

MethodsDescription
add()It adds an item to the set, if the item is already available, it won’t function
clear()It deleted the entire items from the set.
copy()It collects a lower copy of the main set.
difference_update()It’s a modifier that removes similar items also present in a named set.
discard()It removes the isolated item from the set.
intersection()It collects all the elements present in both sets to form a new one
intersection_update()It removes the items from the main set that are not present in both the sets
Isdisjoint()Signifies True if two sets have a null intersection.
Issubset))Signifies if another set contains the main set.
Issuperset()Signifies whether a set carries another set.
pop()Remove and signify the last element of the set. Returns ‘key error’ if the set is empty.
remove itemRemove a member element from a set otherwise it raises KeyError.
symmetric_difference()Remove a member element from a set otherwise it raises KeyError.
symmetric_difference_update()Update a set with the symmetric difference of other set and itself
union()Joins all the elements of sets and forms a new set with it
update()Update a set with the union of its elements and others

Summary

The python set is the unordered collection of comma-separated data enclosed in curly brackets {}. A set is mutable but its items must be immutable. Sets are used to store multiple data in variables, it enables you to carry out similar operations on different items at once

There are two types of sets in Python which are:

  • The set
  • The Frozen set

The set is Known for:

  • Sets are unordered. This means that any item can come before any.
  • Set doesn’t allow repeated elements.
  • A set can be mutable but its items must be immutable
  • Set can contain any type of elements like float, string, integers, and tuple

A set can be created by enclosing an unclose item on curly brackets {}. You can as well execute. some sets using the set() function.

On this page you learned:

  • What is a Python Set?
  • Types of python set
  • Characteristics of the Python Set
  • How to create a Python set
  • How to modify
  • Deleting elements.in Python set
  • Built-in python set methods

You’ve been Python up! Put knowledge into practice, don’t stop until you’re what you dreamt of before taking the first step. Good Luck!

Hi, I’m Pramod Kumar Yadav & a computer science Engineer with 3years of experience in Digital marketing. I’m self-motivated and love to do SEO.

Leave a Reply

%d bloggers like this: