n00bprogrammer22 n00bprogrammer22 - 1 month ago 16
Python Question

Finding last occurrence of a character in a list of lists

I'm writing a function that needs to return the row, and column of the last occurrence of a certain character in a list of lists. If the character isn't in the list of lists the function should return None. The function ignores or skips the first occurrences and then returns the row and col of the last occurrence as an ordered pair.

Example:

lst = [['.','.','.','e'],
['A','A','.','e'],
['.','.','.','e'],
['.','X','X','X'],
['.','.','.','.'],
['.','y','Z','Z']]

#For this list of lists the function should return (5,3) for Z since it is in the 6th list,
#and is the 6th value (python starts the count at 0) and for X it should return (3,3)


I think my current code finds the row and column of the first occurrence of a character but not the last occurrence. How could I instruct Python to ignore the first occurrences and instead return the row and col of the last one?

Code:

def get_far_end(symbol,lot):
for i in range(len(lot)):
for j in lot[i]:
if j == symbol:
return i ,lot[i].index(j)

Answer

Start from end and go backwards:

def get_far_end(symbol,lot):
    for i in range(len(lot)-1,-1,-1):
        for j in range(len(lot[i])-1,-1,-1):
            if lot[i][j] == symbol:
                return i ,j
    return None