Skip to content

Informatics Practices · Ch 4 — Working with Lists and Dictionaries

List Manipulation

4.5

List Manipulation

Everything learnt so far — creating lists, indexing them, and the methods append(), insert(), extend(), pop(), remove(), sort() — comes together in complete programs. The three programs below show the standard patterns of list manipulation: a menu-driven editor for a list, building a list from user input to compute an average, and searching a list for a value.

Program 4-1 — a menu-driven program for list operations

The task: let the user perform any one of these operations on a list, chosen from a menu —

  1. Append an element
  2. Insert an element at the desired position
  3. Append a list to the given list
  4. Modify an existing element
  5. Delete an existing element by its position
  6. Delete an existing element by its value
  7. Sort the list in ascending order
  8. Sort the list in descending order
  9. Display the list

The program starts with myList = [22, 4, 16, 38, 13] (five elements) and gives the user three attempts, one menu choice per attempt, using for attempt in range(3). Each pass prints the current contents of the list, shows the menu, reads a choice with int(input(...)), and dispatches to the matching operation through an if–elif ladder:

# Menu driven program to do various list operations
myList = [22, 4, 16, 38, 13]      # myList having 5 elements
choice = 0
for attempt in range(3):
    print("Attempt number:", attempt)
    print("The list 'myList' has the following elements", myList)
    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")
    choice = int(input("ENTER YOUR CHOICE (1-9): "))

    # append element
    if choice == 1:
        element = eval(input("Enter the element to be appended: "))
        myList.append(element)
        print("The element has been appended\n")

    # insert an element at desired position
    elif choice == 2:
        element = eval(input("Enter the element to be inserted: "))
        pos = int(input("Enter the position:"))
        myList.insert(pos, element)
        print("The element has been inserted\n")

    # append a list to the given list
    elif choice == 3:
        newList = eval(input("Enter the list to be appended: "))
        myList.extend(newList)
        print("The list has been appended\n")

    # modify an existing element
    elif choice == 4:
        i = int(input("Enter the position of the element to be modified: "))
        if i < len(myList):
            newElement = eval(input("Enter the new element: "))
            oldElement = myList[i]
            myList[i] = newElement
            print("The element", oldElement, "has been modified\n")
        else:
            print("Position of the element is more than the length of list")

    # delete an existing element by position
    elif choice == 5:
        i = int(input("Enter the position of the element to be deleted: "))
        if i < len(myList):
            element = myList.pop(i)
            print("The element", element, "has been deleted\n")
        else:
            print("\nPosition of the element is more than the length of list")

    # delete an existing element by value
    elif choice == 6:
        element = int(input("\nEnter the element to be deleted: "))
        if element in myList:
            myList.remove(element)
            print("\nThe element", element, "has been deleted\n")
        else:
            print("\nElement", element, "is not present in the list")

    # list in sorted order
    elif choice == 7:
        myList.sort()
        print("\nThe list has been sorted")

    # list in reverse sorted order
    elif choice == 8:
        myList.sort(reverse = True)
        print("\nThe list has been sorted in reverse order")

    # display the list
    elif choice == 9:
        print("\nThe list is:", myList)

    else:
        print("Choice is not valid")

Design points worth noticing:

  • eval(input(...)) for elements — the element to append or insert is read with eval() so the user may type a number, a string, or even a list, and it is taken as that type; option 3 relies on this to read an entire list to pass to extend().
  • Position safety — the modify and delete-by-position branches first check i < len(myList); if the given position is beyond the list, the program reports it instead of crashing with an out-of-range error.
  • Value safety — the delete-by-value branch first tests element in myList with the membership operator, printing a message when the value is absent rather than letting remove() raise an error.
  • The right method per job — append() for a single element at the end, insert(pos, element) for a chosen position, extend() to merge a list, plain index assignment myList[i] = newElement to modify, pop(i) to delete by position, remove(element) to delete by value, sort() and sort(reverse = True) for the two sort orders.
  • The trailing else catches any choice outside 1–9 and prints "Choice is not valid".

A sample run behaves like this: on the first attempt the list shows [22, 4, 16, 38, 13]; choosing 8 sorts it in reverse order to [38, 22, 16, 13, 4]. On the second attempt, choosing 5 and giving position 2 deletes the element 16, leaving [38, 22, 13, 4]. On the third attempt an out-of-menu entry such as 10 just prints that the choice is not valid.

Program 4-2 — average marks of n students

The task: calculate the average marks of n students, where n is entered by the user. The pattern is build the list, then traverse it:

# create an empty list
list1 = []
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())
    # append marks in the list
    list1.append(marks)

# initialize total
total = 0
for marks in list1:
    # add marks to total
    total = total + marks
average = total / n
print("Average marks of", n, "students is:", average)

The first loop runs n times, reading one student's marks per pass and growing the list with append() — starting from an empty list []. The second loop traverses the finished list, accumulating each element into total (initialised to 0 before the loop). The average is then total / n. With 5 students scoring 45, 89, 79, 76 and 55, the program prints an average of 68.8.

Program 4-3 — searching for a number in a list

The task: check whether a number is present in the list; if it is, print its position, otherwise print an appropriate message.