Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

17.set in Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Courses

Free Courses Interview Questions Tutorials Community

Home /
Tutorial /
Python Sets

Python Sets
By Manoj 6.6 K Views 20  min read Updated on March 9, 2022

In this module of the Python tutorial, we will learn in detail about the set data type in Python. We will further learn the
advantages of the set data type over the list data type. This module also highlights topics such as how to instantiate a Set and
various operations in sets, and toward the end of this module we will also learn about various methods in Python set data type.

Become a Certified Professional

Python Tutorial
Variables

Numbers in Python

String in Python

Python Lists

Tuple in Python

Python Sets

Python Dictionary

Python Operators

Type conversion in
Python

Python If Else
Statements

Python While Loop

For Loop in Python

Python Functions -
Define & Call a Functions
in Python

Lambda Function in
Python

Python Built in
Functions with Examples

Python Arrays

Python Classes and


Objects
Python Modules

Python Dates

Python JSON

Python RegEx

PIP Python

Python File Handling -


How to Create, Open,
Read & Write

Exception Handling in
Python

Enumerate Function in
Python

Python Queue

Python Set
A set in Python is mutable, iterable, and does not have any duplicate elements. It is an unordered collection of elements
which means that a set is a collection that stores elements of different Python Data Types. Remember that a set in Python
doesn’t index the elements in a particular order. Let us look at some of the properties of sets in Python. Sets in Python are
usually used to perform some mathematical functions such as union, intersection, etc.

In Python sets, elements don’t have a specific order.


Sets in Python can’t have duplicates. Each item is unique.
The elements of a set in Python are immutable. They can’t accept changes once added.
But, don’t get confused with the fact that sets in Python are mutable. Python sets allow addition and deletion
operations.

Become a master of Python by going through this online Python Course in Toronto!

One of the major advantages of using sets in Python is that unlike some other data types like Python Lists, sets contain a
highly optimized method for the sole purpose of checking whether a particular element is included in a set or not.

Also, since sets in Python are mutable, we can add and remove elements from a set; however, every element that is added
in the set must be unique and immutable, that is, we cannot change elements once they have been added.

In this module, we will learn all about sets in order to get started with them. Following is the list of all topics that we will be
covering.

Instantiate a Set in Python


Python Set Operations
Common Python Set Functions
Frozenset in Python
Python Ordered Set
Difference between set and list in Python
Convert list to set in Python
Convert set to list in Python

So, without any further delay, let’s get started.

Instantiate a Set in Python


1. Using commas to separate and curly braces to group elements

myset = {“apple”, “banana”, “cherry”}

print(myset)

Output:

{‘cherry’, ‘banana’, ‘apple’}

2. Using the in-built set() method with the elements that we want to add as the parameters

myset = set((“apple”, “banana”, “cherry”)) # note the double round-brackets

print(myset)

Output:

{‘cherry’, ‘banana’, ‘apple’}

Remember that once a set is created we can’t change that set. We can only add elements. We can remove and then add
elements but cannot change the existing elements. Now, let us see how to add items in a Python set.

Python Set operations

Adding Elements to a Set in Python


1. Using the add() method with the element as the parameter:

myset = {“apple”, “banana”, “cherry”}

myset.add(“orange”)

print(myset)

Output:

{‘cherry’, ‘orange’, ‘banana’, ‘apple’}

2. Using update()

myset = {“apple”, “banana”, “cherry”}

myset.update([“orange”, “mango”, “grapes”])

print(myset)

Output:

{‘cherry’, ‘mango’, ‘banana’, ‘apple’, ‘orange’, ‘grapes’}

Get certified by this top Python Course in Singapore today!

Removing elements from sets in Python


Remove operation can be performed by using the following methods.

1. Using the remove() method:

myset = {“apple”, “banana”, “cherry”}

myset.remove(“banana”)

print(myset)

output:

{‘cherry’, ‘apple’}

Note: If the item to be removed does not exist, remove() will raise an error.
2. Using discard():

myset = {“apple”, “banana”, “cherry”}

myset.discard(“banana”)

print(myset)

Output:

{‘cherry’, ‘apple’}

Note: If the item to be removed does not exist, discard() will not raise an error.

3. Using pop():

Remember that pop() will remove the last item of a set. Since sets are unordered, we should avoid performing pop() in sets.

myset = {“apple”, “banana”, “cherry”}

x = myset.pop()

print(x)

print(myset)

Output:

{‘banana’, ‘apple’}

Printing the Length of a Set in Python


To print the length of a set, we can simply use the in-built len() method as shown below:

myset = {“apple”, “banana”, “cherry”}

print(len(myset))

Output:

Emptying a Python Set Completely


To clear a set completely, we can use either the clear() method or the del() method.

1. Using clear():

myset = {“apple”, “banana”, “cherry”}

myset.clear()

print(myset)

2. Using del():

myset = {“apple”, “banana”, “cherry”}

del myset

print(myset)

Output:

Traceback (most recent call last):

File “”, line 1, in

NameError: name ‘myset’ is not defined

As discussed above, sets in Python are used to carry out mathematical set operations such as union, intersection, etc. Let’s
see a few examples of these mathematical operations.
Learn end-to-end Python concepts through the Python Course in Hyderabad to take your career to a whole new level!

Sets Union
To perform union, we use “|” operator. We can also use an in-built method called union(), which will give the same result.

The result of the union of two sets, say Set A and Set B, is a set containing the elements of both sets.

The following code block shows the union of Set A and Set B:

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

Set_B = {4,5,6,7}

print(Set_A | Set_B)

Output:

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

Set Intersection
To perform an intersection, we use ‘&’ operator. We can also use the in-built Python Function named intersection() to get
the same result.

The intersection of two sets say Set A and Set B, can result in a set that contains the elements that are common in both
sets, that is, the overlapping part in the diagram below.

The following code block shows the union of Set A and Set B:

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

Set_B = {4,5,6,7}

print (Set_A & Set_B)

Output:

{4, 5}

Are you interested in learning Python from experts? Enroll in our Python Course in Bangalore now!

Common Python Set functions

Method Description

update() It updates a set with the union of this set and others.

add() It adds an element to a set.

clear() It removes all elements from a set.

copy() It returns a copy of a set.

difference() It returns a set containing the difference between two or more sets.

difference_update() It removes the items in a set that are also included in another, specified set.

discard() It removes a specified item.


remove() It removes a specified element.

pop() It removes an element from a set.

intersection() It returns a set, that is the intersection of two other sets.

intersection_update() It removes items in a set that are not present in another, specified set(s).

isdisjoint() It returns whether two sets have an intersection or not.

issubset() It returns whether another set contains a specific set or not.

issuperset() It returns whether a set contains another set or not.

symmetric_difference() It returns a set with the symmetric differences of two sets.

union() or | It returns a set containing the union of sets.

intersection or & It returns a set comprising common elements in two sets.

Frozenset in Python
frozenset() is an inbuilt Python function that takes an iterable object as input and makes it immutable. It Simply freezes the
iterable objects and makes them unchangeable. The frozenset() function returns an unchangeable frozenset object (which
is like a set object, only unchangeable).

In Python, frozenset() is the same as set except the forzensets are immutable which means that elements from the
frozenset cannot be added or removed once created. This function takes input as any iterable object and converts them
into an immutable object. The order of elements is not guaranteed to be preserved.

mylist = ['apple', 'banana', 'cherry']

x = frozenset(mylist)

print(x)

The output will be

frozenset({'cherry', 'banana', 'apple'})

Python Ordered Set


There aren’t ordered sets in Python, but programmers can use collections.OrderedDict from the Python standard library
with just keys and the values as none.

OrderedSet([1, 2, 3])

Difference between set and list in Python

Set List

Sets are mutable Lists are immutable

Sets are unordered collections of items Lists are ordered collections of items

Items can’t be replaced or changed. Items can be changed or replaced.

You might also like