33. Searching and editing list items

  • The index number of the list item allows you to edit and delete particular items once located
  • This example uses the in operator to quickly check the whole list
  • If the search term exists, it then looks up the index, and uses this to directly edit the name “Sarah”, changing it to “Sara”
#List containing 4 names
names = [‘Joe’,’Mike’,’Sarah’,’Charlie’]

#Checking a list using 'in' and IF
name = 'Sarah'
if name in names:

    #Print found name message
    print(name + " found at location: ")

    #Grab index number of current name and print
    index = names.index(name)
    print(index)

    #Use the index to change the item
    names[index] = “Sara”

    #Use the index to delete the item
    names.pop(index)

Tasks

  1. Type in the code and make sure it works
  2. Modify the program to ask the user for a name, search for it and allow the user to update it if found
  3. Save and label your code

Extension Task

This ‘search’ technique is essential knowledge because you must be able to search in order to delete, or edit items in a list that already exists. Can you modify the program to offer an option of edit (or) delete if the name is found?