0% found this document useful (0 votes)
25 views29 pages

module 5 py1

Uploaded by

dhruvaroyal07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views29 pages

module 5 py1

Uploaded by

dhruvaroyal07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Python-Set

• Set:Creating a set, adding items to the set,


removing items from the set, remove (),
Python Set Operations: Union, Intersection,
Difference, Symmetric Difference, Set
comparisons, Python Built-in set methods,
Sample Programs.
Definition of the 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
Example
My_Print= {10, ‘z’, 7}
print (My_Print)
Output:-
{10, ‘z’, 7}
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).
My_Print= {10, ‘Hi’, (7)}
print (My_Print)
// {10, ‘Hi’, (7)}
Creating Python Sets

• A set is created by placing all the items


(elements) inside curly braces {}, separated by
comma, or by using the built-in set() function.
• It can have any number of items and they may
be of different types (integer, float, tuple,
string etc.). But a set cannot have mutable
elements like lists, sets or dictionaries as its
elements.
Examples
my_set = {1, 2, 3}
print(my_set)
{1, 2, 3}
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
{1.0, (1, 2, 3), 'Hello'}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# Output: {1, 2, 3,4}
my_set = set([1, 2, 3, 2])
print(my_set)
Output:{1, 2, 3}
# set cannot have mutable items
# here [3, 4] is a mutable list
# this will cause an error.
my_set = {1, 2, [3, 4]}
Output: Error
creating empty set
a = set()
print(type(a))
<class 'set'>
Suppose
a = {}
print(type(a))
<class 'dict'>
Modifying a set in Python

• Sets are mutable. However, since they are


unordered, indexing has no meaning.
• We cannot access or change an element of a set
using indexing or slicing. Set data type does not
support it.
• We can add a single element using
the add() method, and multiple elements using
the update() method. The update() method can
take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.
my_set = {1, 3}
print(my_set)
Output:{1,2}
# add an element
my_set.add(2)
print(my_set)
# Output: {1, 2, 3}
# add multiple elements
my_set.update([2, 3, 4])
print(my_set)
# Output: {1, 2, 3, 4}
# add list and set
my_set.update([4, 5], {1, 6, 8})
print(my_set)
# Output: {1, 2, 3, 4, 5, 6, 8}
Removing elements from a set

• A particular item can be removed from a set


using the methods discard() and remove().
• The only difference between the two is that
the discard() function leaves a set unchanged
if the element is not present in the set. On the
other hand, the remove() function will raise an
error in such a condition (if element is not
present in the set).
# Difference between discard() and remove()

# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
my_set.discard(4)
print(my_set)
# Output: {1, 3, 5, 6}
# remove an element
my_set.remove(6)
print(my_set)
# Output: {1, 3, 5}
# discard an element
# not present in my_set
my_set.discard(2)
print(my_set)
# Output: {1, 3, 5}
# remove an element
# not present in my_set
# you will get an error.
my_set.remove(2)
# Output: KeyError
Characteristics of set
• 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.
Set operations
• Finding the set length
• Access the set
• Removing the set
• Union of set
• Set Intersections
• Difference of set
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.
Example
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}
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.
• You can either use the & operator or
intersection() method in this case.
a={1, 0, 5, 2.0}
b={1,5,'abc'}
c={1,3,4,}
print(a&b)
print(a&b&c)
output:-
{1,5}
{1}
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.
Example
a={10, 20,50, 4.6, 'x', 'y'}
b={20,50,'d'}
print(a-b)
o/p:-
{10, 4.6, ‘x’, ‘y’}
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.
• Symmetric Difference of A and B is a set of
elements in A and B but not in both (excluding
the intersection).
• Symmetric difference is performed
using ^ operator. Same can be accomplished
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}

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A ^ B)
Output: {1, 2, 3, 6, 7, 8}
Built-in Functions with Set
• Built-infunctions like all(), any(), enumerate(),
len(), max(), min(), sorted(), sum() etc. are commonly
used with sets to perform different tasks.
• FunctionDescription
• all()Returns True if all elements of the set are true (or if
the set is empty).
• any()Returns True if any element of the set is true. If the
set is empty, returns False.
• enumerate()Returns an enumerate object. It contains
the index and value for all the items of the set as a pair.
• len()Returns the length (the number of
items) in the set.
• max()Returns the largest item in the set.
• min()Returns the smallest item in the set.
• sorted()Returns a new sorted list from
elements in the set(does not sort the set
itself).
• sum()Returns the sum of all elements in the
set.
Other Python Set Methods
• There are many set methods, some of which we have
already used above. Here is a list of all the methods that
are available with the set objects:
• add()Adds an element to the set
• clear()Removes all elements from the set
• copy()Returns a copy of the set
• difference()Returns the difference of two or more sets as a
new set
• difference_update()Removes all elements of another set
from this set
• discard()Removes an element from the set if it is a
member. (Do nothing if the element is not in set)
• intersection()Returns the intersection of two sets as a new
set
• intersection_update()Updates the set with the
intersection of itself and another
• isdisjoint()Returns True if two sets have a null intersection
• issubset()Returns True if another set contains this set
• issuperset()Returns True if this set contains another set
• pop()Removes and returns an arbitrary set element.
Raises KeyError if the set is empty
• remove()Removes an element from the set. If the
element is not a member, raises a KeyError
• symmetric_difference()Returns the symmetric difference
of two sets as a new set
• symmetric_difference_update()Updates a set with the
symmetric difference of itself and another
• union()Returns the union of sets in a new set
• update()Updates the set with the union of itself and

You might also like