0% found this document useful (0 votes)
151 views

List in Python Final PPT.pptx

Uploaded by

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

List in Python Final PPT.pptx

Uploaded by

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

LIST IN PYTHON

Mutable data type


List – Creating and Initializing list 2
• The data type list is an ordered sequence of comma separated values
(elements/objects) enclosed in square brackets [].
• The values in a list may be of different types (integer, float, string, list, tuple
etc.) – Heterogeneous data type.
• Lists are mutable i.e. values in a list can be edited /changed.
L1 = [] #Empty list
L1 = [‘English’, 45, ‘Maths’, 86, ‘Rajesh’, 1234]
L2 = [12, 15, ‘Manish’, [45, 87], 23] #Nested List
L3 = [‘Sonia’, (‘E001’, ‘D001’), 34000] # Tuple within a list
L = [1,"abc",(23,12),[23,"str"],{1:"A",2:"B"}]
# number, string, tuple, list, dict
Accessing List by Index 3

List items can be accessed by using their index or indices


Forward
Index
Backward
Index
L = ["Eng",65,"Maths",97, "Sc.",89]
print(L[3]) 97
print(L[1+4]) 89
print(L[2*2]) Sc.
print(L[5-4+1]) Maths
Accessing List by Index 3

L = ["Eng",65,"Maths",97, "Sc.",89]
Lists are Mutable : Change data in the list 5
List operations – Concatenation 6

Concatenation: It takes ‘+’ operator to concatenate with another list.


Correct
A = [12, 43] A = [12,43]
C = [12, 43, 34, 78]
B = [34, 78] A = A + [5]
A [12, 43, 34, 78]
C=A+B B= [34, 78, 12, 43, 34, 78]
print("C = ",C)
A=A+B TypeError: can only
print("A = ",A) A = [12, 43]
concatenate list (not "int")
B += A A=A+5
to list
print("B = ",B)
List operations – Repetition 7

Repetition: It takes ‘*’ operator to repeat the list content by the


given number.

L = [12, 43] [12 , 43, 12, 43]


print(L * 2) [1, 'Amit', 1, 'Amit', 1, 'Amit']]
L1 = [1,"Amit"]
print(3 * L1)
L = [12, 43] Type Error: can't multiply
L2 = [3] sequ ence by non-int value
print(L * L2)
List operations –Membership 8

Membership: It check whether the given element is present in


the list or not. It uses
in : The given element is present.
not in: The given element is not present.
L = [12, 43]
L1 = [1,"Amit"] Tru e
print("Amit" in L1) Fal se
print(12 not in L)
Accessing List - Slicing 4
Slicing
[ start index : end index : step ]
The default of start index is 0, step is 1. It will display data from
start index to end-1 index.
L = ["Eng",65,"Maths",97, "Sc.",89]
print(L[ :4]) ['Eng', 65, 'Maths', 97]
print(L[2: ]) ['Maths', 97, 'Sc.', 89]
print(L[ : ]) ['Eng', 65, 'Maths', 97, 'Sc.' , 89]
print(L[ : :-1]) [89, 'Sc.', 97, 'Maths', 65, ' Eng’]
Print(L[ : : 2]) [‘Eng’,’Maths’,’Sc.’]
Traversing a List 9
There are two ways to traverse the list.
1. Element / Member
2. Index – 0, 1, …len(L) - 1
L = [12,"Amit",[23,43,29]]
for i in L:
print(i, end = " ") 12 Amit [23, 43, 29]
print()
12 Amit [23, 43, 29]
for i in range(len(L)):
print(L[i],end = " ")
Traversing a List – To add number five to each element 10
in the list.

L = [12, 43, 17, 34, 29]


print("Initial list is: ", L)
print("After adding 5: ", end = "")
for i in range(len(L)): Initial list is: [12, 43, 17, 34, 29]
L[i] += 5 After adding 5: [17, 48, 22, 39, 34]
print(L)
List methods – len(), append(), extend() 11
L = [14,32,29]
L1 = [22,25]
print(L,len(L)) [14, 32, 29] 3
L.append(L1) After append [14, 32, 29, [22, 25]] 4
print(“After
append”,L,len(L)) [14, 32, 29] 3
After extend [14, 32, 29, 22, 25] 5
L = [14,32,29]
print(L,len(L)) append(): It adds the object as one element.
extend(): It adds the elements in the object as
L1 = [22,25] individual element in the list.
L.extend(L1)
print(“After extend”,L,len(L))
List methods – count(),insert(),remove() 12
count(): It counts the given data present in the list.
insert(): It inserts the data at a given location in the list.
remove(): It removes the given data in a list, whichever comes first from the left to right.
L = [14,32,29,28,32,14,28] [14, 32, 29, 28, 32, 14, 28]
print(L)
Count of 14: 2
print("Count of 14: ",L.count(14))
L.insert(3,14) [14, 32, 29, 14, 28, 32, 14, 28]
print(L) Count of 14: 3
print("Count of 14: ",L.count(14)) [32, 29, 28, 32, 14, 28]
L.remove(14) Count of 14: 1
L.remove(14)
print(L)
print("Count of 14: ",L.count(14))
List methods – reverse(), sort() 13
reverse(): it reverses the order of elements in the list.
sort(): It sorts the data in the list in ascending order.
sort(reverse = True): it sorts the data in the list in descending order.
Note: In sort(), it works with homogeneous data type.
L = [14,32,29,28,12,24] [14, 32, 29, 28, 12, 24]
print(L) List in reverse order:
L.reverse() [24, 12, 28, 29, 32, 14]
print("List in reverse order:",L) List in ascending order:
L.sort() [12, 14, 24, 28, 29, 32]
print("List in ascending order:",L) List in descending order:
L.sort(reverse = True) [32, 29, 28, 24, 14, 12]
print("List in descending order:",L)
List methods – sort() in string data type 14

L = ["Zen","Ben","Arif","Kity"]
print("Original list", L,sep = ‘\n’) Original list
L.sort() ['Zen', 'Ben', 'Arif', 'Kity']
List in Ascending order
print("List in Ascending order",L,sep = ‘\n’) ['Arif', 'Ben', 'Kity', 'Zen']
L.sort(reverse = True) List in Descending order
print("List in Descending order",L,sep = ‘\n’) ['Zen', 'Kity', 'Ben', 'Arif']
List methods – sort() in nested list 15

L = [[23,12],[34,45],[22,11]]
print("Original list", L,sep = ‘\n’)) Original list [[23, 12], [34,
L.sort() 45], [22, 11]]
List in Ascending order
print("List in Ascending order",L,sep = ‘\n’) [[22, 11], [23, 12], [34, 45]]
L.sort(reverse = True) List in Descending order
print("List in Descending order",L,sep = ‘\n’)) [[34, 45], [23, 12], [22, 11]]
List methods – sort() vs sorted 16

L = [12,9,5,2,3]
print("Original list", L)
Original list [12, 9, 5, 2, 3]
L1 = sorted(L) List in Ascending order [2, 3, 5, 9, 12]
print("List in Ascending order",L1) List in Descending order [12, 9, 5, 3, 2]
L1 = sorted(L,reverse = True)
print("List in Descending order",L1)
List methods – sort() vs sorted 17

L = ["Zen","Ben","Arif","Kity"]
print("Original list", L)
L1 = sorted(L)
print("List in Ascending order",L1)
L1 = sorted(L,reverse = True)
print("List in Descending order",L1)

Original list ['Zen', 'Ben', 'Arif', 'Kity']


List in Ascending order ['Arif', 'Ben', 'Kity', 'Zen']
List in Descending order ['Zen', 'Kity', 'Ben', 'Arif']
List methods – pop(), del 18
pop(): It deletes the element mentioned as index. The default index is -1.
del : It deletes the element mentioned as index, otherwise it deletes the entire list
permanently.
L = [14,32,29,28,12,24] [14, 32, 29, 28, 12, 24]
print(L) Remove the -1 index value:
print("Remove the -1 index value:“) 24
[14, 32, 29, 28, 12]
L.pop() ; print(L) Remove the 2 index value:
print("Remove the 2 index value:“) 29
L.pop(2) ; print(L) [14, 32, 28, 12]
print("Remove the 1 index value:“ Remove the 1 index value:
[14, 28, 12]
del L[1] ; print(L)
Delete the entire list
print("Delete the entire list") NameError: name 'L' is not defined12]
del L ; print(L)
List methods – index() 19

L = [14,32,29,32,12,24]
print(L) [14, 32, 29, 32, 12, 24]
print("Index of 32 from left",end ="") Index of 32 from left 1
print(L.index(32)) Index of 32 after index 2 3
print("Index of 32 after index 2",end ="") Index of 40 not present
print(L.index(32,2)) ValueError: 40 is not in list
print("Index of 40 not present",end ="")
print(L.index(40))
List built-in functions – min(),max(),sum() 20
max(): It returns the maximum value in the list.
min(): it returns the minimum value in the list.
sum(): it returns the sum of all the values in the list.

Note: min(), max() works with number or string data type.


sum() works with number data type only.

L = [14,32,29,32,12,24]
print(L) [14 , 32, 29, 32, 12, 24]
print("Maximum:",max(L)) M aximum: 32
print("Minimum:",min(L)) Mi nimum: 12
print("Sum:",sum(L)) Sum : 143
print("Average:",round(sum(L)/len(L),2)) Av erage: 23.83
Nested List

When a list appears as an element of another list, it is called a nested list.

To access the element of the nested list of list1, we have to specify two indices list1[i][j]. The first
index i will take us to the desired nested list and second index j will take us to the desired
element in that nested list

>>> list1=[1,2,'a','c',[6,7,8],4,9]
>>> list1[4]
[6, 7, 8]
>>> list1[4][1]
7
Copying Lists
The simplest way to make a copy of the list is to assign it to another list.

>>> list1 = [1,2,3]


>>> list2 = list1
>>> list1
[1, 2, 3]
>>> list2
[1, 2, 3]
The statement list2 = list1 does not create a new list. Rather, it just makes list1 and list2 refer to
the same list object. Here list2 actually becomes an alias of list1. Therefore, any changes made
to either of them will be reflected in the other list.

>>> list1.append(10)
>>> list1
[1, 2, 3, 10]
>>> list2
[1, 2, 3, 10
We can also create a copy or clone of the list as a distinct object by three methods. The first method
uses slicing, the second method uses built-in function list() and the third method uses copy() function of
python library copy.

Method 1

We can slice our original list and store it into a new variable as follows:

newList = oldList[:]

Example
>>> list1 = [1,2,3,4,5]
>>> list2 = list1[:]
>>> list2
[1, 2, 3, 4, 5]
Method 2 Method 3
We can use the built-in function list() as follows: We can use the copy () function as follows:
import copy #import the library copy
newList = list(oldList) #use copy()function of library copy

newList = copy.copy(oldList)

Example
Example
>>> import copy
>>> list1 = [10,20,30,40]
>>> list1 = [1,2,3,4,5]
>>> list2 = list(list1)
>>> list2 = copy.copy(list1)
>>> list2 [10, 20, 30, 40]
>>> list2 [1, 2, 3, 4, 5]
Program 1: To input number of marks to be entered, enter
marks and add in a list and display the average marks.

n = int(input("Enter no. of marks to be


entered")) Enter number of marks to be entered 4
Enter marks 2
L = [] Enter marks 3
for i in range(n): Enter marks 4
Enter marks 5
marks = int(input("Enter marks")) Average of [2, 3, 4, 5] is 3.5
L.append(marks)
s=0
for i in L:
s += i
avg=s/n
print("Average of ", L, “ is “, avg)
Program 2: To input number of marks, enter marks, search whether
the given mark is present at location or not. 22
L = []
n = int(input("How many numbers")) How many numbers5
Enter number21
for i in range(n): Enter number23
n = int(input("Enter number")) Enter number20
L.append(n) Enter number17
num = int(input("Enter the number Enter number19
to be searched: ")) Enter the number to be searched
pos = -1 Number 20 is present at 2 positio
for i in range(n):
if L[i] == num: pos = i ; break
if pos == -1 : print("Number",num,"is not present")
else: print("Number",num,"is present at",pos, "position")
Sangita Panchal
Program 3: A menu driven program of list, to do the following:
1. Add a data
2. Insert a data
3. Add list
4. Modify data by index
5. Delete by value
6. Delete by position
7. Sort in ascending order
8. Sort in descending order
9. display list
L = []
while True:
print("""1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display""")
choice = int(input("Enter the choice"))
if choice == 1:
n = int(input("Enter data"))
L.append(n) ; print(L)
elif choice == 2:
n = int(input("Enter data"))
pos = int(input("Enter position"))
L.insert(pos,n) ; print(L)
elif choice == 3:
nList = eval(input("Enter the list to be appended: "))
L.extend(nList) ; print(L)
elif choice == 4:
i = int(input("Enter the data position to modified: "))
if i < len(L):
num = eval(input("Enter the new element: "))
L[i] = num
else:
print("Position not in the list")
print(L)
elif choice == 5:
i = int(input("Enter the element position to be deleted: "))
if i < len(L):
num = L.pop(i)
else:
print("\nPosition not in the list")
print(L)
elif choice == 6:
num = int(input("\nEnter the element to be deleted: "))
if num in L:
L.remove(num)
else:
print("\nElement",element,"is not present in the list")
elif choice == 7:
L.sort()
elif choice == 8:
L.sort(reverse = True)
elif choice == 9:
print("\nThe list is:", L)
else:
print("Exit")
break
1 append, 2 insert, 3 append list, Enter the choice3
4 - modify, 5 - Delete by position, Enter the list to be appended: 25,21,20
6 - Delete by value, 7 - sort in ascending [23, 18, 25, 21, 20]
8 - Sort in descending, 9- Display 1 append, 2 insert, 3 append list,
Enter the choice1 4 - modify, 5 - Delete by position,
Enter data18 6 - Delete by value, 7 - sort in ascending
[18] 8 - Sort in descending, 9- Display
1 append, 2 insert, 3 append list, Enter the choice4
4 - modify, 5 - Delete by position, Enter the data position to modified: 2
6 - Delete by value, 7 - sort in ascending Enter the new element: 15
8 - Sort in descending, 9- Display [23, 18, 15, 21, 20]
Enter the choice2 1 append, 2 insert, 3 append list,
Enter data23 4 - modify, 5 - Delete by position,
Enter position0 6 - Delete by value, 7 - sort in ascending
[23, 18] 8 - Sort in descending, 9- Display
1 append, 2 insert, 3 append list, Enter the choice5
4 - modify, 5 - Delete by position, Enter the element position to be deleted: 1
6 - Delete by value, 7 - sort in ascending [23, 15, 21, 20] l
1 append, 2 insert, 3 append list, Enter the choice8
4 - modify, 5 - Delete by position, [23, 20, 15]
6 - Delete by value, 7 - sort in ascending 1 append, 2 insert, 3 append list,
8 - Sort in descending, 9- Display 4 - modify, 5 - Delete by position,
Enter the choice6 6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the element to be deleted: 21 Enter the choice9
[23, 15, 20]
1 append, 2 insert, 3 append list, The list is: [23, 20, 15]
4 - modify, 5 - Delete by position, 1 append, 2 insert, 3 append list,
6 - Delete by value, 7 - sort in ascending 4 - modify, 5 - Delete by position,
8 - Sort in descending, 9- Display 6 - Delete by value, 7 - sort in ascending
Enter the choice7 8 - Sort in descending, 9- Display
[15, 20, 23] Enter the choice10
1 append, 2 insert, 3 append list, Exit
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice1
Enter your name samy
Enter your phone number2134
Continue Y/Ny
Enter your name joe
Enter your phone number4343
Continue Y/Nn
{'samy': '2134', 'joe': '4343'}
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice2
Enter the name whose phone number you want to
modifiedjoe Enter the modified phone number1111
The dictionary is = {'samy': '2134', 'joe': '1111'}
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice3
Namesam
y Present
1 create/add, 2 modify, 3 search, 4 sort, 5
exit Enter choice4
joe : 1111,samy : 2134,1 create/add, 2 modify, 3 search, 4 sort, 5
exit Enter choice5
End of program
NCERT PRACTICAL QUESTIONS

#Write a program to find the number of times an element occurs in the list
L=eval(input('Enter a list '))
num=eval(input('Enter the number to be searched '))
c=L.count(num)
print('Number ',num, ' occurs ',c, ' number of times')

Enter a list [32,45,45.5,67,77]


Enter the number to be searched 45
Number 45 occurs 1 number of times
>>>

Enter a list [56,66,34,56,67,78,56]


Enter the number to be searched 56
Number 56 occurs 3 number of times
#Write a program to read a list of n integers (positive, as well as negative).
#Create two new lists, one having all positive numbers and the other having
#all negative numbers from the given list.
#print all the three lists

L=eval(input('Enter the list of numbers '))


L1=[ ] # list for negative numbers
L2=[ ] # List for negative numbers
for i in range(len(L)):
if L[i]<0:
L1.append(L[i]) Enter the list of numbers [56,-4,5,-3,45.5,-23,5,7,-78]
else: Original List is [56, -4, 5, -3, 45.5, -23, 5, 7, -78]
L2.append(L[i]) List with negative numbers is [-4, -3, -23, -78]
print('Original List is ',L) List with positive numbers is [56, 5, 45.5, 5, 7]
print ('List with negative numbers is ',L1)
print('List with positive numbers is ',L2)
#Write a program to read a list of elements. Modify this list so that it does
# not contain any duplicate elements, i.e., all elements occurring multiple
# times in the list should appear only once
L=eval(input('Enter items of the list '))
newL=[]
for i in L:
if i not in newL:
newL.append(i)
print('Original list is ', L)
print('New list without duplicate values is ',newL)
Enter items of the list [12,23,45,12,15,17,23]
Original list is [12, 23, 45, 12, 15, 17, 23]
New list without duplicate values is [12, 23, 45, 15, 17]
# Write a program to read a list of elements. Input an element from the user
# that has to be inserted in the list. Also input the position at which
# it is to be inserted.
L=eval(input('Enter the list '))
num=eval(input('Enter the number to be inserted '))
pos=int(input('Enter the position where new element is to be inserted '))
L.insert(pos,num)
print('New List is ', L)
Enter the list [12,34,78,34.5,56]
Enter the number to be inserted 88
Enter the position where new element is to be inserted 2
New List is [12, 34, 88, 78, 34.5, 56]
# Write a program to read elements of a list. The program should ask the
# position of the element to be deleted from the list. Print the new list
L=eval(input('Enter the list '))
pos=int(input('Enter the position of the item to be deleted '))
L.pop(pos)
print(' New List is ',L)

Enter the list [12,34,45,11,23,55]


Enter the position of the item to be deleted 3
New List is [12, 34, 45, 23, 55]
# Write a program to read elements in a list. The program should ask the
# value of element to be deleted from the list
L=eval(input('Enter the list '))
num=eval(input('Enter value to be deleted '))
L.remove(num)
print(' New list is ',L)

Enter the list [23,12,45,11,13,16,17]


Enter value to be deleted 11
New list is [23, 12, 45, 13, 16, 17]

You might also like