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]
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
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
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