Menu

Two-dimensional Arrays (2D Lists)

Searching a 2D List

A linear search on a 2D list checks each row in turn. You compare the field that holds the search key — for example, the name column — with the value you want. Stop as soon as you find a match, because checking the remaining rows wastes time.

Keep a separate variable for the result, such as a found flag or the matching row index, instead of changing the stored values. The original 2D list should stay unchanged unless the task asks you to update it. If you only need to know whether a record exists, one match is enough. If you need every match, still make just one pass over the rows and collect each match as you go. A well-designed solution visits each record as few times as possible rather than making repeated passes over the whole structure.

This program searches a list of club records. Each row holds a club name and its meeting day. It stops at the first match and reports the day without altering the list.

clubs = [["Chess", "Monday"], ["Coding", "Wednesday"], ["Art", "Friday"], ["Drama", "Thursday"]]
search_name = input("Club to find: ")
found = False
row = 0
while row < len(clubs) and not found:
    if clubs[row][0] == search_name:
        found = True
        meeting_day = clubs[row][1]
    else:
        row = row + 1

if found:
    print(search_name + " meets on " + meeting_day)
else:
    print(search_name + " was not found")

Output when the user types Art:

Club to find: Art
Art meets on Friday

Practise this