Week 9.2 (SET)
Week 9.2 (SET)
Week 9.2 (SET)
01 02 03
SET SET CREATION SET METHODS
04 05 06
SET MUTATION FROZEN SET
SET OPERATIONS
Set-{}
• A Python set is the collection of the unordered heterogenous
items.
• Set elements are unique. Duplicate elements are not allowed.
• A set is mutable, but the elements contained in the set must be of Set is mutable but
an immutable type. its element must
be immutable
• There is no index attached to the elements of the set.
• Set items are unordered, unchangeable, and do not allow
duplicate values.
• Set items are unchangeable, meaning that we cannot change the
items after the set has been created. Once a set is created, you
cannot change its items, but you can remove items and add new Eg:{2,4,1,7,8,9}
items.
Set Creation
⮚ The set can be created by enclosing the comma-separated immutable
items with the curly braces {}.
⮚ Python also provides the set() method, which can be used to create the set
by the passed sequence.
Output is unordered
Access the items in set
Built-in method-Adding Elements
The add() method is used to add a single
element to the set.
Adding
Element
The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists,
dictionaries etc.).
Built-in method-Deleting Elements
The discard method is used to remove an
item from the set.
Deleting
Element
⮚ The elements of the frozen set cannot be changed after the creation.
⮚ We cannot change or append the content of the frozen sets by using the methods
like add() or remove().
⮚ The iterable sequence is passed into this method which is converted into the
frozen set as a return type of the method.
Frozenset
Hint
Point 1:The set list is unordered, so the result will display the items in a
random order.
Write a Python program that takes a complete sentence as an input and remove
duplicate word in it and then counts all the words which have a length greater than 3.
Input:
“we are good are we good”
Output:
we are good
Count=1
Example 2
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input:
112
Output:
12
Example 2:
Input:
11233
Output:
123
Example 3
Given two lists, print all the common element of two lists.
Note: Sort the list before printing.
Examples:
Input :
12345
56789
Output :
5
Input :
12345
6789
Output :
No common elements
Example 4
Two strings are said to be complete if on concatenation, they contain all the 26 English
alphabets. For example, “abcdefghi” and “jklmnopqrstuvwxyz” are complete as they
together have all characters from ‘a’ to ‘z’.