Computer Science · Ch 9 — Lists
List Manipulation
List Manipulation
This closing section pulls the whole chapter together: creating lists, and applying the operations and methods learnt so far, inside complete working programs. Three programs are developed — a menu-driven list editor, an average-marks calculator, and a linear search — each exercising a different slice of the list toolkit.
Program 1 — a menu-driven program for list operations
The first program keeps a list alive across an interactive session and lets the user manipulate it through a numbered menu, performing operations such as:
- Append an element
- Insert an element at a desired position
- Append a whole list to the given list
- Modify an existing element
- Delete an element by its position
- Delete an element by its value
- Sort the list in ascending order
- Sort the list in descending order
- Display the list
The structure is an infinite while True: loop that shows the menu, reads a choice with int(input()), and dispatches with an if/elif chain; the exit choice uses break to leave the loop.
# Menu driven program to do various list operations
data = [31, 7, 24, 50, 18] # data already has 5 elements
choice = 0
while True:
print("The list 'data' has the following elements", data)
print("\nL I S T O P E R A T I O N S")
print(" 1. Append an element")
print(" 2. Insert an element at the desired position")
print(" 3. Append a list to the given list")
print(" 4. Modify an existing element")
print(" 5. Delete an existing element by its position")
print(" 6. Delete an existing element by its value")
print(" 7. Sort the list in ascending order")
print(" 8. Sort the list in descending order")
print(" 9. Display the list")
print(" 10. Exit")
choice = int(input("ENTER YOUR CHOICE (1-10): "))
if choice == 1: # append an element
element = int(input("Enter the element to be appended: "))
data.append(element)
print("The element has been appended\n")
elif choice == 2: # insert at a desired position
element = int(input("Enter the element to be inserted: "))
pos = int(input("Enter the position: "))
data.insert(pos, element)
print("The element has been inserted\n")
elif choice == 3: # append a list to the list
newItems = eval(input("Enter the elements separated by commas: "))
data.extend(list(newItems))
print("The list has been appended\n")
elif choice == 4: # modify an existing element
i = int(input("Enter the position of the element to be modified: "))
if i < len(data):
newElement = int(input("Enter the new element: "))
oldElement = data[i]
data[i] = newElement
print("The element", oldElement, "has been modified\n")
else:
print("Position of the element is more than the length of list")
elif choice == 5: # delete by position
i = int(input("Enter the position of the element to be deleted: "))
if i < len(data):
element = data.pop(i)
print("The element", element, "has been deleted\n")
else:
print("\nPosition of the element is more than the length of list")
elif choice == 6: # delete by value
element = int(input("\nEnter the element to be deleted: "))
if element in data:
data.remove(element)
print("\nThe element", element, "has been deleted\n")
else:
print("\nElement", element, "is not present in the list")
elif choice == 7: # ascending sort
data.sort()
print("\nThe list has been sorted")
elif choice == 8: # descending sort
data.sort(reverse = True)
print("\nThe list has been sorted in reverse order")
elif choice == 9: # display
print("\nThe list is:", data)
elif choice == 10: # exit the menu
break
else:
print("Choice is not valid")
print("\n\nPress any key to continue..............")
ch = input()
A sample of the interaction — choosing option 8 (descending sort) and then option 5 (delete by position):
The list 'data' has the following elements [31, 7, 24, 50, 18]
ENTER YOUR CHOICE (1-10): 8
The list has been sorted in reverse order
The list 'data' has the following elements [50, 31, 24, 18, 7]
ENTER YOUR CHOICE (1-10): 5
Enter the position of the element to be deleted: 2
The element 24 has been deleted
The list 'data' has the following elements [50, 31, 18, 7]
Points worth noticing:
- Choices 4 and 5 validate the position (
i < len(data)) before indexing, avoiding an IndexError. - Choice 6 uses the membership operator
inbefore callingremove(), avoiding a ValueError. - Choice 3 reads several comma-separated values with
eval(input(...))and merges them viaextend(list(...))— element by element, not as one nested element.
Program 2 — average marks of n students using a function
The second program builds a list dynamically: it starts from an empty list, reads n marks from the user in a loop, appending each one, and then passes the list (plus n) to a function that totals the marks by traversal and returns the average.
# Function to calculate average marks of n students
def computeAverage(mlist, n):
total = 0 # initialize total
for marks in mlist:
total = total + marks # add marks to total
average = total / n
return average
mlist = [] # create an empty list
print("How many students marks you want to enter: ")
n = int(input())
for i in range(0, n):
print("Enter marks of student", (i + 1), ":")
marks = int(input())
mlist.append(marks) # append marks in the list
average = computeAverage(mlist, n)
print("Average marks of", n, "students is:", average)
Sample run:
How many students marks you want to enter:
4
Enter marks of student 1 :
62
Enter marks of student 2 :
80
Enter marks of student 3 :
74
Enter marks of student 4 :
56
Average marks of 4 students is: 68.0
The pattern empty list → loop → append() is the standard way to collect user input of unknown size into a list.
Program 3 — searching a list with a user-defined function
The last program checks whether a number is present in a list. A user-defined function walks the list index by index (a linear search); if it finds the number it returns the position, and if the loop finishes without a match it returns None. The caller then prints an appropriate message for each case.