Wednesday, August 21, 2019

Examples of List In Python

Suppose we have following data and we want to perform some operations on this data through List in python:

Name
Marks
Ravi
79
Mohan
83
Shyam
76
Shakshi
77
Pawan
67
Rashmi
81
Rakesh
70

Operation 1: Store above data in a List and Print Marks of Rashmi.

name = ["Ravi", "Mohan", "Shyam", "Shakshi", "Pawan", "Rashmi", "Rakesh"]
marks=[79,83,76,77,67,81,70]
print("Marks of Rashmi is :", marks[5])

Operation 2: Change Marks of Pawan as 71.

marks[4]= 71
print("Marks of Pawan is :", marks[4])

Operation 3: Find out number of Students

print("Number of Students is :", len(name))

Operation 4: Append one more students data : Neelam is student name and Marks is 89

name.append("Neelam")
marks.append(89)
print(name)
print(marks)

Operation 5: Add following more data in List at the end :


Name
Marks
Rajesh
76
Sarvesh
87
Piyush
56

name.extend(["Rajesh", "Sarvesh", "Piyush"])
marks.extend([76,87,56])
print(name)
print(marks)

Operation 6 : Insert one more students data at Index Number 2: Geeta having marks 72

name.insert(2, "Geeta")
marks.insert(2, 72)
print(name)
print(marks)

Operation 7 : Delete data of last student from list

name.pop()
marks.pop()
print(name)
print(marks)

Operation 8: Remove data of Pawan having marks 67 from the list

name.remove("Pawan")
marks.remove(67)
print(name)
print(marks)

Operation 9 : Find out all students data from index 2 to 5

print(name[2:6])
print(marks[2:6])

This is called Slicing of List. Also observe that end index provided in program is 6 instead of 5.









No comments:

Post a Comment