- Searching through two-dimensional lists is best done with a FOR loop
- Each time, you can use an IF statement to check a particular part of the list item
- Sorting a 2D list is easy as long as the field to sort by is the first item (first name in the example below)
#Create a new list, each list item containing three items
users = [
["Mike","Smith",24],
["John","Thompson",56],
["Mary","Field",19],
["Katie","Johnson",15]
]
#Name to search for
searchSurname = input("Enter surname: ")
#Loop. If the name is found, the location will be printed
for user in users:
#Compare the searchSurname to the name in the list
if user[1] == searchSurname:
#Get & print the index location of the matching name
foundat = users.index(user)
print("Found at index: ",foundat)
#Ask if the user wishes to delete the record
q = input("Press (y) to delete this record: ")
#If the user chooses 'y' 0111111111111111
if q == "y":
#Delete the record using the index
users.pop(foundat)
#Sort and print the list once the loop has finished
users.sort()
print(users)
Tasks
- Type in the code above and make sure that it works
- Add 3 more people into the original list
- Modify the program to search for first name
- Save and label your code
Extension Task
Investigate how this program reacts if there are duplicate names in the list. What happens when you search and there are two people named ‘Smith’ for example? You can also modify this code to allow the editing of a name if it is found