SlideShare a Scribd company logo
1 of 52
Aswini
AP/CSE
LISTS
 List is a sequence of values called items or elements
 The elements can be of any datatype
 The list is a most versatile datatype available in
Python which can be written as a list of comma-
separated values (items) between square brackets.
 List are mutable, meaning, their elements can be
changed
Method -1 without
constructor
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
# nested list
my_list = [“welcome", [8, 4, 6]]
Method-2 using list constructor
# empty list
my_list = list()
# list of integers
my_list = list([1, 2, 3])
• In Python programming, a list is created by placing all the items
(elements) inside a square bracket [ ], separated by commas.
• It can have any number of items and they may be of different types
(integer, float, string etc.).
 index operator [] is used to access an item in a list. Index starts
from 0
 marks=[90,80,50,70,60]
 print(marks[0])
Output: 90
 Nested list:
 my_list = [“welcome", [8, 4, 6]]
 Print(marks[1][0])
Output: 8
#Slicing
>>> marks=[90,80,50,70,60]
>>> marks[1:3]
[80, 50]
#Slicing-to reverse the list
>>> marks[::-1]
[60, 70, 50, 80, 90]
 Python allows negative indexing for its sequences.The index of
-1 refers to the last item, -2 to the second last item and so on
my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])
# Output: p
print(my_list[-5])
we can also get a list of individual elements by looping through
the set.
marks=[90,60,50,80,70]
for m in marks:
print(m)
Output:
90
60
50
80
70
#Change Elements
= operator
>>> marks=[90,60,80]
>>> print(marks)
[90, 60, 80]
>>> marks[1]=100
>>> print(marks)
[90, 100, 80]
#Add Elements
 add one item to a list using
append() method
>>> marks.append(50)
>>> print(marks)
[90, 100, 80, 50]
add several items using extend()
>>> marks.extend([60,80,70])
>>> print(marks)
[90, 100, 80, 50, 60, 80, 70]
insert one item at a desired location
by using the method insert()
>>> marks.insert(3,40)
>>> print(marks)
[90, 100, 80, 40, 50, 60, 80, 70]
 delete one or more items from
a list using the keyword del.
 It can even delete the list
entirely.
>>>marks=[90,100,80,40,50,60,
30,70]
>>> del marks[6]
>>> print(marks)
[90, 100, 80, 40, 50, 60, 70]
>>> del marks
>>> print(marks)
NameError: name 'marks' is not
defined
 clear() method to empty a list.
>>> marks.clear()
>>> print(marks)
[]
 remove() method to remove the
given item
>>> marks=[90,60,80]
>>> marks.remove(80)
>>> print(marks)
[90, 60]
pop() method to remove an item at
the given index.
>>> marks=[100,20,30]
>>> marks.pop()
30
>>> print(marks)
[100, 20]
>>> >>> marks.pop(0)
100
>>> print(marks)
[20]
delete items in a list
by assigning an
empty list to a slice
of elements.
marks=[100,20,30]
>>> marks[1:3]=[]
>>> print(marks)
[100]
 = operator to create a copy of an object. It doesn't creates new
object. It only creates a new variable that shares the reference of
the original object.
 Changes made with one alias affect the other.
>>> old=["c",1,"python",2]
>>> new=old
>>> id(old)
36780632
>>> id(new)
36780632
>>> old is new
True
>>>
 Copy method
>>> old=["c",1,"python",2]
>>> new=old.copy()
>>> id(new)
27708312
>>> id(old)
36780752
>>> old is new
False
 Copy module:
 copy(), deepcopy()
functions
 Using slicing[:]
>>> old=["c",1,"python",2]
>>> new=old[:]
>>> id(new)
27707232
>>> id(old)
36780752
>>> old is new
False
Description Python Expression Output
Concatenation + [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6]
Repetition * ['Hi!‘] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!‘]
Membership in 3 in [1, 2, 3] True
Identity is L1=[1,2,3]
L2=L1
L1 is L2
L3=L1.copy()
L1 is L3
True
False
 A string is a sequence of characters and list is a sequence of
values, but list of character is not same as string.
 To convert string to a list of characters
>>> p="python"
>>> print(p)
python
>>> l=list(p)
>>> print(l)
['p', 'y', 't', 'h', 'o', 'n']
>>>
Function Description
all()
Return True if all elements of the List are true (or if the set is
empty).
any()
Return True if any element of the List is true. If the set is
empty, return False.
len() Return the length (the number of items) in the list.
list() Convert an iterable (tuple, string, set, dictionary) to a list.
max() Return the largest item in the list.
min() Return the smallest item in the list
sorted() Return a new sorted list (does not sort the list itself).
sum() Return the sum of all elements in the list.
random.shuffle() Shuffles the elements randomly
reversed()
returns an iterator that accesses the given sequence in
the reverse order.
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an
argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
PASSING LIST TO A FUNCTION:
 As list is mutable object, A programmer can pass a list to a
function and can perform various operations on it.
 We can change the contents of a list after passing it to a
function.
 Passing a list to a function is just like passing an object to a
function
RETURNING LIST FROM A FUNCTION
 A function can return a list.
 List’s reference value is returned
 Write a function to reverse the list
def reverse(lst):
print("Original list=",lst)
lst.reverse()
return lst
lst=[90,80,70,60,50]
print("Reversed list=",reverse(lst))
Output:
Original list= [90, 80, 70, 60, 50]
Reversed list= [50, 60, 70, 80, 90]
 Write a function Split_list(lst,n) where list is split into two parts
and length of the first part is given as n
def split_list(lst,n):
list1=lst[:n]
list2=lst[n:]
return list1,list2
lst=[100,20,60,80,95,60,20,65,40]
print("List before splitting")
print("list=",lst)
list1,list2=split_list(lst,4)
print("List After splitting")
print("List1=",list1)
print("list2=",list2)
Output:
List before splitting
list= [100, 20, 60, 80, 95, 60, 20, 65, 40]
List After splitting
List1= [100, 20, 60, 80]
list2= [95, 60, 20, 65, 40]
 List comprehension is used to create a new list from existing sequences.
 It is a tool for transforming a given list into another list
 Example: create a list to store 5 nos 10,20,30,40,50,using for loop add 5
to each element of the list
Syntax: [<expression> for <element> in <sequence> if <condition>]
Without list comprehension using list comprehension
>>> list1=[10,20,30,40,50] >>> list1=[10,20,30,40,50]
>>>list2=[] >>> list2=[x+5 for x in list1]
>>> list1 >>> list2
[10, 20, 30, 40, 50] [15, 25, 35, 45, 55]
>>> for i in range(0,len(list1)):
list2.append(list1[i]+5)
>>> list2
[15, 25, 35, 45, 55]
Write a program to display the even elements of a list
>>> marks=[90,65,30,60,70,80,15,20,99,100]
>>> marks_below_50
[30, 15, 20]
>>> marks
[90, 65, 30, 60, 70, 80, 15, 20, 99, 100]
>>> marks_below_50=[m for m in marks if m<50]
 Consider a list with five different Celsius values. Convert all the
Celsius values into Fahrenheit
 1.What is printed by the following statements?
alist = [4,2,8,6,5]
blist = [num*2 for num in alist if num%2==0]
print(blist)
 Output:
(A) [4,2,8,6,5]
(B) [8,4,16,12]
(C) [10]
 Searching is a technique of quickly finding a specific item from
a given list of items.
 Linear Search
 Binary Search
 Elements are examined sequentially starting from the first
element.
 Element to be searched(key) is compared sequentially with
each element in a list
 Search process terminates when the element to be searched is
found or the list is exhausted
 If key matches with an element in the list, return the index.
 If key doesn’t match with any of elements, return -1.
def linear_search(My_list, key):
"""Return index of key in a list. Return -1 if
key not present."""
for i in range(len(My_list)):
if My_list[i] == key:
return i
return -1
My_list = [50,60,25,29,63,98,65]
print(My_list)
key = int(input('The number to search for: '))
index = linear_search(My_list, key)
if index == -1:
print(key,"was not found")
else:
print(key, "was found at index",index)
 Output:
#Test Case 1
[50, 60, 25, 29, 63, 98, 65]
The number to search for: 29
29 was found at index 3
#Test Case 2
[50, 60, 25, 29, 63, 98, 65]
The number to search for: 90
90 was not found
 Linear search is not suitable for
large list
 For binary search, the elements in a
list must be in sorted order
 Compare the element to be
searched with the middle of the list,
 If the key is less than the middle
element then, we have to search only
in the first half of the list
 If the key is greater than the middle
element, then we have to search only
in the second half of the list
 If the element to be found is equal to
the middle element in the list then the
search ends
 If the element to be found is not
present within the list then returns
None or -1
def binary_search(My_list,key):
low=0
high=len(My_list)-1
while low<=high:
mid=(low+high)//2 #find the mid index
if My_list[mid]==key:
return mid
elif key>My_list[mid]:
low=mid+1
else:
high=mid-1
return -1 #if no match return -1
My_list=[10,20,50,60,70,80,90]
print(Mylist)
key=int(input("Enter the number to search:"))
found=binary_search(My_list,key)
if found==-1:
print(key,"is not present in the list")
else:
print("The element",key,"is found at index",found)
 Output:
#Test Case 1
[10,20,50,60,70,80,90]
Enter the number to search:30
30 is not present in the list
#Test Case 2
[10,20,50,60,70,80,90]
Enter the number to search:60
The element 60 is found at index 2
 Sorting means rearranging the elements of a list, so that they
organized in ascending /descending order
 Bubble sort
 Selection sort
 It is the simplest and oldest sorting
algorithm
 Sorts the list of elements by
repeatedly moving the largest
element to the highest index position
of the list
 Consecutive adjacent pair of
elements are compared
 If the element at lower index is
greater than the element at higher
index then two elements are
interchanged
 This process is repeated till the list of
unsorted elements is exhausted
 The algorithm derives its name as
bubble sort because the smaller
elements bubble to the top of the list
def bubble_sort(mylist):
for i in range(len(mylist)-1,0,-1):
for j in range(i):
if mylist[j]>mylist[j+1]:
mylist[j],mylist[j+1]=mylist[j+1],mylist[j]
mylist=[50,40,30,20,10]
print("Before Sortingn",mylist)
bubble_sort(mylist)
print("After sortingn",mylist)
Output:
Before Sorting
[50, 40, 30, 20, 10]
After sorting
[10, 20, 30, 40, 50]
 The selection sort improves on the
bubble sort by making only one
exchange for every pass through
the list.
 Selection sort is conceptually the
most simplest sorting algorithm.
 This algorithm will first find
the smallest element in the array
and swap it with the element in
the first position,
 then it will find the second
smallest element and swap it with
the element in the second position,
 and it will keep on doing this until
the entire array is sorted.
 It is called selection sort because it
repeatedly selects the next-
smallest element and swaps it into
the right place.
def selection_sort(mylist):
for i in range(len(mylist)-1):
smallest=i
for j in range(i+1,len(mylist)):
if mylist[smallest]>mylist[j]:
smallest=j
if smallest!=i:
mylist[smallest], mylist[i] = mylist[i], mylist[smallest]
mylist=[500,400,300,200,100]
print("Before Sortingn",mylist)
selection_sort(mylist)
print("After sortingn",mylist)
Output:
Before Sorting
[500, 400, 300, 200, 100]
After sorting
[100, 200, 300, 400, 500]
SETS
SET
ELEMENTS
A set is an unordered collection of items.
Every element is unique (no duplicates)
and must be immutable (which cannot be
changed).
However, the set itself is mutable.We can
add or remove items from it.
Sets can be used to perform
mathematical set operations like union,
intersection, symmetric difference etc.
SET
ELEMENTS
Unlike lists, where the elements are
stored as ordered list, the order of
elements in a set is undefined .
Any immutable data type can be an
element of a set: a number, a string, a
tuple.
Mutable (changeable) data types
cannot be elements of the set.
In particular, list cannot be an element
of a set (but tuple can), and another
set cannot be an element of a set.
Method 1
 A set is created by placing all
the items (elements) inside
curly braces {}
>>> roll_no={1,2,3,4,5}
>>> print(roll_no)
{1, 2, 3, 4, 5}
>>> student={'aaa',1,'bbb',2}
>>> print(student)
{'aaa', 1, 2, 'bbb'}
Method 2
using set()
>>> emp_id=set({401,402,403,404})
>>> print(emp_id)
{401, 402, 403, 404}
>>> roll_no=set([61,62,63])
>>> print(roll_no)
{61, 62, 63}
 cannot access individual values in a set.We can only access all
the elements together.
print(roll_no)
But we can also get a list of individual elements by looping
through the set.
Days={"Mon","Tue","Wed","Thu","Fri","Sat","Sun“}
for d in Days:
print(d)
CREATING AN EMPTY SET
IS A BIT TRICKY.
 Empty curly braces {} will
make an empty dictionary
in Python.
 To make a set without any
elements we use the set()
function without any
argument.
>>> s={}
>>> type(s)
<class 'dict'>
>>> s=set()
>>> type(s)
<class 'set'>
HOW TO
CHANGE A
SET IN
PYTHON?
Sets are mutable. But since they are
unordered, indexing have no meaning.
We cannot access or change an
element of set using indexing or
slicing. Set does not support it.
We can add 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.
 add() method
 Add single element
>>> roll_no
{1, 2, 3, 4, 5}
>>> roll_no.add(6)
>>> print(roll_no)
{1, 2, 3, 4, 5, 6}
 update() method
 Add multiple elements using the
 can take tuples, lists, strings or other
sets as its argument.
 In all cases, duplicates are avoided.
>>> roll_no.update({7,8})
>>> print(roll_no)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> l_no=[9,10]
>>> roll_no.update(l_no)
>>> print(roll_no)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
 remove() method
remove() will raise an error in if the
element not found
>>> roll_no.remove(6)
>>> print(roll_no)
Output: {1, 2, 3, 4, 5, 7, 8, 9, 10}
>>> roll_no.remove(12)
Traceback (most recent call last):
KeyError: 12
discard() method
>>> roll_no.discard(10)
>>> print(roll_no)
Output: {1, 2, 3, 4, 5, 7, 8, 9}
>>> roll_no.discard(11)
>>> roll_no
Output: {1, 2, 3, 4, 5, 7, 8, 9}
 pop() method
Set being unordered, there is no way of
determining which item will be popped.
It is completely arbitrary.
>>> roll_no.pop()
Output: 1
 clear() method
remove all items
>>> roll_no.clear()
>>> roll_no
Output; set()
 del
>>> del roll_no
>>> roll_no
NameError: name 'roll_no' is not defined
 Sets can be used to carry out mathematical set operations like
 Union
 Intersection
 difference
 Symmetric difference
| operator
>>>print(a | b)
{1, 2, 3, 4, 5, 6, 7, 8}
Union() mehtod
>>> print(a.union(b))
{1, 2, 3, 4, 5, 6, 7, 8}
>>> print(b.union(a))
{1, 2, 3, 4, 5, 6, 7, 8}
& operator
>>> print(a&b)
{4, 5}
intersection() method
>>> print(a.intersection(b))
{4, 5}
>>> print(b.intersection(a))
{4, 5}
Intersection of A and B is a set of
elements that are common in both sets.
- operator
 >>> print(a-b)
 {1, 2, 3}
 >>> print(b-a)
 {8, 6, 7}
difference() method
 >>> print(a.difference(b))
 {1, 2, 3}
 >>> print(b.difference(a))
 {8, 6, 7}
Difference of a and b (a - b) is a set of elements that
are only in a but not in b.
Similarly, b - a is a set of element in b but not in a.
^ operator
 >>> print(a^b)
 {1, 2, 3, 6,7,8}
Symmetric_difference()
 >>> print(a.symmetric_difference(b))
 {1, 2, 3, 6,7,8}
 >>> print(b.symmetric_difference(a))
 {1, 2, 3, 6,7,8}
Symmetric Difference of A and B is a set of
elements in both A and B except those that are
common in both.
Python Set Methods
Method Description
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 arbitary set element.
Raise KeyError if the set is empty
remove()
Removes an element from the set. If the element is not a
member, raise 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 others
Built-in Functions with Set
Function Description
all()
Return True if all elements of the set are true (or if the set is
empty).
any()
Return True if any element of the set is true. If the set is
empty, return False.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
sorted()
Return a new sorted list from elements in the set(does not
sort the set itself).
sum() Return the sum of all elements in the set.
 In Software company, the following are the employees:
Coders={‘Aishwarya’,’Ambrish’,’Mohanahari’,’Dhivya’,’Nivetha’}
Analysts={‘Mohanahari’,’Nivetha’,’Karthini’,’Janani’,’Archana’}
Write a python program to find
1. Employees working as coders as well as analysts - c & a
2. Employees working as coders or analysts – c | a
3. Employees working as coders but not analysts – c-a
4. Employees working as analysts but not coders – a-c
5. Employees working in only one group- a^c
c-coders, a-analysts
Consider the sets:
Predict the output.
Answer:
 Find the output of the following Python code
s1 = set("my name is John and John is my name".split())
 Don’t consider the order of the words
A. error
B. s1 = {'is', 'and', 'my', 'name', 'John'}
C. s1 = ('is', 'and', 'my', 'name', 'John')
D. s1 = {'my' 'name' 'is' 'John' 'and' 'John' 'is' 'my' 'name'}
 Answer=b

More Related Content

What's hot (20)

Singly link list
Singly link listSingly link list
Singly link list
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
Python list
Python listPython list
Python list
 
Linked list
Linked listLinked list
Linked list
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
Python strings
Python stringsPython strings
Python strings
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
Python list
Python listPython list
Python list
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search tree
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
 
Python functions
Python functionsPython functions
Python functions
 

Similar to Python lists &amp; sets (20)

List in Python
List in PythonList in Python
List in Python
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
Pytho lists
Pytho listsPytho lists
Pytho lists
 
List Data Structure.docx
List Data Structure.docxList Data Structure.docx
List Data Structure.docx
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt
 
Python PCEP Lists Collections of Data
Python PCEP Lists Collections of DataPython PCEP Lists Collections of Data
Python PCEP Lists Collections of Data
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202
 
LIST IN PYTHON PART-2
LIST IN PYTHON PART-2LIST IN PYTHON PART-2
LIST IN PYTHON PART-2
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Python lists
Python listsPython lists
Python lists
 
Pytho_tuples
Pytho_tuplesPytho_tuples
Pytho_tuples
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 

Recently uploaded

Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniquesugginaramesh
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 

Recently uploaded (20)

Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Comparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization TechniquesComparative Analysis of Text Summarization Techniques
Comparative Analysis of Text Summarization Techniques
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 

Python lists &amp; sets

  • 3.  List is a sequence of values called items or elements  The elements can be of any datatype  The list is a most versatile datatype available in Python which can be written as a list of comma- separated values (items) between square brackets.  List are mutable, meaning, their elements can be changed
  • 4. Method -1 without constructor # empty list my_list = [] # list of integers my_list = [1, 2, 3] # list with mixed datatypes my_list = [1, "Hello", 3.4] # nested list my_list = [“welcome", [8, 4, 6]] Method-2 using list constructor # empty list my_list = list() # list of integers my_list = list([1, 2, 3]) • In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated by commas. • It can have any number of items and they may be of different types (integer, float, string etc.).
  • 5.  index operator [] is used to access an item in a list. Index starts from 0  marks=[90,80,50,70,60]  print(marks[0]) Output: 90  Nested list:  my_list = [“welcome", [8, 4, 6]]  Print(marks[1][0]) Output: 8 #Slicing >>> marks=[90,80,50,70,60] >>> marks[1:3] [80, 50] #Slicing-to reverse the list >>> marks[::-1] [60, 70, 50, 80, 90]
  • 6.  Python allows negative indexing for its sequences.The index of -1 refers to the last item, -2 to the second last item and so on my_list = ['p','r','o','b','e'] # Output: e print(my_list[-1]) # Output: p print(my_list[-5])
  • 7. we can also get a list of individual elements by looping through the set. marks=[90,60,50,80,70] for m in marks: print(m) Output: 90 60 50 80 70
  • 8. #Change Elements = operator >>> marks=[90,60,80] >>> print(marks) [90, 60, 80] >>> marks[1]=100 >>> print(marks) [90, 100, 80] #Add Elements  add one item to a list using append() method >>> marks.append(50) >>> print(marks) [90, 100, 80, 50] add several items using extend() >>> marks.extend([60,80,70]) >>> print(marks) [90, 100, 80, 50, 60, 80, 70] insert one item at a desired location by using the method insert() >>> marks.insert(3,40) >>> print(marks) [90, 100, 80, 40, 50, 60, 80, 70]
  • 9.  delete one or more items from a list using the keyword del.  It can even delete the list entirely. >>>marks=[90,100,80,40,50,60, 30,70] >>> del marks[6] >>> print(marks) [90, 100, 80, 40, 50, 60, 70] >>> del marks >>> print(marks) NameError: name 'marks' is not defined  clear() method to empty a list. >>> marks.clear() >>> print(marks) []  remove() method to remove the given item >>> marks=[90,60,80] >>> marks.remove(80) >>> print(marks) [90, 60] pop() method to remove an item at the given index. >>> marks=[100,20,30] >>> marks.pop() 30 >>> print(marks) [100, 20] >>> >>> marks.pop(0) 100 >>> print(marks) [20] delete items in a list by assigning an empty list to a slice of elements. marks=[100,20,30] >>> marks[1:3]=[] >>> print(marks) [100]
  • 10.  = operator to create a copy of an object. It doesn't creates new object. It only creates a new variable that shares the reference of the original object.  Changes made with one alias affect the other. >>> old=["c",1,"python",2] >>> new=old >>> id(old) 36780632 >>> id(new) 36780632 >>> old is new True >>>
  • 11.  Copy method >>> old=["c",1,"python",2] >>> new=old.copy() >>> id(new) 27708312 >>> id(old) 36780752 >>> old is new False  Copy module:  copy(), deepcopy() functions  Using slicing[:] >>> old=["c",1,"python",2] >>> new=old[:] >>> id(new) 27707232 >>> id(old) 36780752 >>> old is new False
  • 12. Description Python Expression Output Concatenation + [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Repetition * ['Hi!‘] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!‘] Membership in 3 in [1, 2, 3] True Identity is L1=[1,2,3] L2=L1 L1 is L2 L3=L1.copy() L1 is L3 True False
  • 13.  A string is a sequence of characters and list is a sequence of values, but list of character is not same as string.  To convert string to a list of characters >>> p="python" >>> print(p) python >>> l=list(p) >>> print(l) ['p', 'y', 't', 'h', 'o', 'n'] >>>
  • 14. Function Description all() Return True if all elements of the List are true (or if the set is empty). any() Return True if any element of the List is true. If the set is empty, return False. len() Return the length (the number of items) in the list. list() Convert an iterable (tuple, string, set, dictionary) to a list. max() Return the largest item in the list. min() Return the smallest item in the list sorted() Return a new sorted list (does not sort the list itself). sum() Return the sum of all elements in the list. random.shuffle() Shuffles the elements randomly reversed() returns an iterator that accesses the given sequence in the reverse order.
  • 15. append() - Add an element to the end of the list extend() - Add all elements of a list to the another list insert() - Insert an item at the defined index remove() - Removes an item from the list pop() - Removes and returns an element at the given index clear() - Removes all items from the list index() - Returns the index of the first matched item count() - Returns the count of number of items passed as an argument sort() - Sort items in a list in ascending order reverse() - Reverse the order of items in the list copy() - Returns a shallow copy of the list
  • 16. PASSING LIST TO A FUNCTION:  As list is mutable object, A programmer can pass a list to a function and can perform various operations on it.  We can change the contents of a list after passing it to a function.  Passing a list to a function is just like passing an object to a function RETURNING LIST FROM A FUNCTION  A function can return a list.  List’s reference value is returned
  • 17.  Write a function to reverse the list def reverse(lst): print("Original list=",lst) lst.reverse() return lst lst=[90,80,70,60,50] print("Reversed list=",reverse(lst)) Output: Original list= [90, 80, 70, 60, 50] Reversed list= [50, 60, 70, 80, 90]
  • 18.  Write a function Split_list(lst,n) where list is split into two parts and length of the first part is given as n def split_list(lst,n): list1=lst[:n] list2=lst[n:] return list1,list2 lst=[100,20,60,80,95,60,20,65,40] print("List before splitting") print("list=",lst) list1,list2=split_list(lst,4) print("List After splitting") print("List1=",list1) print("list2=",list2) Output: List before splitting list= [100, 20, 60, 80, 95, 60, 20, 65, 40] List After splitting List1= [100, 20, 60, 80] list2= [95, 60, 20, 65, 40]
  • 19.  List comprehension is used to create a new list from existing sequences.  It is a tool for transforming a given list into another list  Example: create a list to store 5 nos 10,20,30,40,50,using for loop add 5 to each element of the list Syntax: [<expression> for <element> in <sequence> if <condition>] Without list comprehension using list comprehension >>> list1=[10,20,30,40,50] >>> list1=[10,20,30,40,50] >>>list2=[] >>> list2=[x+5 for x in list1] >>> list1 >>> list2 [10, 20, 30, 40, 50] [15, 25, 35, 45, 55] >>> for i in range(0,len(list1)): list2.append(list1[i]+5) >>> list2 [15, 25, 35, 45, 55]
  • 20. Write a program to display the even elements of a list >>> marks=[90,65,30,60,70,80,15,20,99,100] >>> marks_below_50 [30, 15, 20] >>> marks [90, 65, 30, 60, 70, 80, 15, 20, 99, 100] >>> marks_below_50=[m for m in marks if m<50]
  • 21.  Consider a list with five different Celsius values. Convert all the Celsius values into Fahrenheit
  • 22.  1.What is printed by the following statements? alist = [4,2,8,6,5] blist = [num*2 for num in alist if num%2==0] print(blist)  Output: (A) [4,2,8,6,5] (B) [8,4,16,12] (C) [10]
  • 23.
  • 24.  Searching is a technique of quickly finding a specific item from a given list of items.  Linear Search  Binary Search
  • 25.  Elements are examined sequentially starting from the first element.  Element to be searched(key) is compared sequentially with each element in a list  Search process terminates when the element to be searched is found or the list is exhausted  If key matches with an element in the list, return the index.  If key doesn’t match with any of elements, return -1.
  • 26. def linear_search(My_list, key): """Return index of key in a list. Return -1 if key not present.""" for i in range(len(My_list)): if My_list[i] == key: return i return -1 My_list = [50,60,25,29,63,98,65] print(My_list) key = int(input('The number to search for: ')) index = linear_search(My_list, key) if index == -1: print(key,"was not found") else: print(key, "was found at index",index)  Output: #Test Case 1 [50, 60, 25, 29, 63, 98, 65] The number to search for: 29 29 was found at index 3 #Test Case 2 [50, 60, 25, 29, 63, 98, 65] The number to search for: 90 90 was not found
  • 27.  Linear search is not suitable for large list  For binary search, the elements in a list must be in sorted order  Compare the element to be searched with the middle of the list,  If the key is less than the middle element then, we have to search only in the first half of the list  If the key is greater than the middle element, then we have to search only in the second half of the list  If the element to be found is equal to the middle element in the list then the search ends  If the element to be found is not present within the list then returns None or -1
  • 28. def binary_search(My_list,key): low=0 high=len(My_list)-1 while low<=high: mid=(low+high)//2 #find the mid index if My_list[mid]==key: return mid elif key>My_list[mid]: low=mid+1 else: high=mid-1 return -1 #if no match return -1 My_list=[10,20,50,60,70,80,90] print(Mylist) key=int(input("Enter the number to search:")) found=binary_search(My_list,key) if found==-1: print(key,"is not present in the list") else: print("The element",key,"is found at index",found)  Output: #Test Case 1 [10,20,50,60,70,80,90] Enter the number to search:30 30 is not present in the list #Test Case 2 [10,20,50,60,70,80,90] Enter the number to search:60 The element 60 is found at index 2
  • 29.  Sorting means rearranging the elements of a list, so that they organized in ascending /descending order  Bubble sort  Selection sort
  • 30.  It is the simplest and oldest sorting algorithm  Sorts the list of elements by repeatedly moving the largest element to the highest index position of the list  Consecutive adjacent pair of elements are compared  If the element at lower index is greater than the element at higher index then two elements are interchanged  This process is repeated till the list of unsorted elements is exhausted  The algorithm derives its name as bubble sort because the smaller elements bubble to the top of the list
  • 31. def bubble_sort(mylist): for i in range(len(mylist)-1,0,-1): for j in range(i): if mylist[j]>mylist[j+1]: mylist[j],mylist[j+1]=mylist[j+1],mylist[j] mylist=[50,40,30,20,10] print("Before Sortingn",mylist) bubble_sort(mylist) print("After sortingn",mylist) Output: Before Sorting [50, 40, 30, 20, 10] After sorting [10, 20, 30, 40, 50]
  • 32.  The selection sort improves on the bubble sort by making only one exchange for every pass through the list.  Selection sort is conceptually the most simplest sorting algorithm.  This algorithm will first find the smallest element in the array and swap it with the element in the first position,  then it will find the second smallest element and swap it with the element in the second position,  and it will keep on doing this until the entire array is sorted.  It is called selection sort because it repeatedly selects the next- smallest element and swaps it into the right place.
  • 33. def selection_sort(mylist): for i in range(len(mylist)-1): smallest=i for j in range(i+1,len(mylist)): if mylist[smallest]>mylist[j]: smallest=j if smallest!=i: mylist[smallest], mylist[i] = mylist[i], mylist[smallest] mylist=[500,400,300,200,100] print("Before Sortingn",mylist) selection_sort(mylist) print("After sortingn",mylist) Output: Before Sorting [500, 400, 300, 200, 100] After sorting [100, 200, 300, 400, 500]
  • 34. SETS
  • 35. SET ELEMENTS A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable (which cannot be changed). However, the set itself is mutable.We can add or remove items from it. Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.
  • 36. SET ELEMENTS Unlike lists, where the elements are stored as ordered list, the order of elements in a set is undefined . Any immutable data type can be an element of a set: a number, a string, a tuple. Mutable (changeable) data types cannot be elements of the set. In particular, list cannot be an element of a set (but tuple can), and another set cannot be an element of a set.
  • 37. Method 1  A set is created by placing all the items (elements) inside curly braces {} >>> roll_no={1,2,3,4,5} >>> print(roll_no) {1, 2, 3, 4, 5} >>> student={'aaa',1,'bbb',2} >>> print(student) {'aaa', 1, 2, 'bbb'} Method 2 using set() >>> emp_id=set({401,402,403,404}) >>> print(emp_id) {401, 402, 403, 404} >>> roll_no=set([61,62,63]) >>> print(roll_no) {61, 62, 63}
  • 38.  cannot access individual values in a set.We can only access all the elements together. print(roll_no) But we can also get a list of individual elements by looping through the set. Days={"Mon","Tue","Wed","Thu","Fri","Sat","Sun“} for d in Days: print(d)
  • 39. CREATING AN EMPTY SET IS A BIT TRICKY.  Empty curly braces {} will make an empty dictionary in Python.  To make a set without any elements we use the set() function without any argument. >>> s={} >>> type(s) <class 'dict'> >>> s=set() >>> type(s) <class 'set'>
  • 40. HOW TO CHANGE A SET IN PYTHON? Sets are mutable. But since they are unordered, indexing have no meaning. We cannot access or change an element of set using indexing or slicing. Set does not support it. We can add 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.
  • 41.  add() method  Add single element >>> roll_no {1, 2, 3, 4, 5} >>> roll_no.add(6) >>> print(roll_no) {1, 2, 3, 4, 5, 6}  update() method  Add multiple elements using the  can take tuples, lists, strings or other sets as its argument.  In all cases, duplicates are avoided. >>> roll_no.update({7,8}) >>> print(roll_no) {1, 2, 3, 4, 5, 6, 7, 8} >>> l_no=[9,10] >>> roll_no.update(l_no) >>> print(roll_no) {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  • 42.  remove() method remove() will raise an error in if the element not found >>> roll_no.remove(6) >>> print(roll_no) Output: {1, 2, 3, 4, 5, 7, 8, 9, 10} >>> roll_no.remove(12) Traceback (most recent call last): KeyError: 12 discard() method >>> roll_no.discard(10) >>> print(roll_no) Output: {1, 2, 3, 4, 5, 7, 8, 9} >>> roll_no.discard(11) >>> roll_no Output: {1, 2, 3, 4, 5, 7, 8, 9}  pop() method Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary. >>> roll_no.pop() Output: 1  clear() method remove all items >>> roll_no.clear() >>> roll_no Output; set()  del >>> del roll_no >>> roll_no NameError: name 'roll_no' is not defined
  • 43.  Sets can be used to carry out mathematical set operations like  Union  Intersection  difference  Symmetric difference
  • 44. | operator >>>print(a | b) {1, 2, 3, 4, 5, 6, 7, 8} Union() mehtod >>> print(a.union(b)) {1, 2, 3, 4, 5, 6, 7, 8} >>> print(b.union(a)) {1, 2, 3, 4, 5, 6, 7, 8}
  • 45. & operator >>> print(a&b) {4, 5} intersection() method >>> print(a.intersection(b)) {4, 5} >>> print(b.intersection(a)) {4, 5} Intersection of A and B is a set of elements that are common in both sets.
  • 46. - operator  >>> print(a-b)  {1, 2, 3}  >>> print(b-a)  {8, 6, 7} difference() method  >>> print(a.difference(b))  {1, 2, 3}  >>> print(b.difference(a))  {8, 6, 7} Difference of a and b (a - b) is a set of elements that are only in a but not in b. Similarly, b - a is a set of element in b but not in a.
  • 47. ^ operator  >>> print(a^b)  {1, 2, 3, 6,7,8} Symmetric_difference()  >>> print(a.symmetric_difference(b))  {1, 2, 3, 6,7,8}  >>> print(b.symmetric_difference(a))  {1, 2, 3, 6,7,8} Symmetric Difference of A and B is a set of elements in both A and B except those that are common in both.
  • 48. Python Set Methods Method Description 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 arbitary set element. Raise KeyError if the set is empty remove() Removes an element from the set. If the element is not a member, raise 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 others
  • 49. Built-in Functions with Set Function Description all() Return True if all elements of the set are true (or if the set is empty). any() Return True if any element of the set is true. If the set is empty, return False. len() Return the length (the number of items) in the set. max() Return the largest item in the set. min() Return the smallest item in the set. sorted() Return a new sorted list from elements in the set(does not sort the set itself). sum() Return the sum of all elements in the set.
  • 50.  In Software company, the following are the employees: Coders={‘Aishwarya’,’Ambrish’,’Mohanahari’,’Dhivya’,’Nivetha’} Analysts={‘Mohanahari’,’Nivetha’,’Karthini’,’Janani’,’Archana’} Write a python program to find 1. Employees working as coders as well as analysts - c & a 2. Employees working as coders or analysts – c | a 3. Employees working as coders but not analysts – c-a 4. Employees working as analysts but not coders – a-c 5. Employees working in only one group- a^c c-coders, a-analysts
  • 51. Consider the sets: Predict the output. Answer:
  • 52.  Find the output of the following Python code s1 = set("my name is John and John is my name".split())  Don’t consider the order of the words A. error B. s1 = {'is', 'and', 'my', 'name', 'John'} C. s1 = ('is', 'and', 'my', 'name', 'John') D. s1 = {'my' 'name' 'is' 'John' 'and' 'John' 'is' 'my' 'name'}  Answer=b