Search code examples
pythonlistpython-3.xpositionsymbols

Returning position of specific symbol in list of lists


For this function I'm writing I want to return the position of a specific character that is closest to the top left of the list of lists. It'd be great to accomplish this in the most basic way without importing modules. Here is the code I have so far then I will explain more about what I'm trying to do

def find_position(symbol,lst): 

# Sample List: [['.','M','M','G','G'],
#               ['.','.','.','.','h'],  
#               ['B','B','B','.','h']]
#
    for sublist in lst:
        for symbol in sublist:
            if symbol == True:
            lst.find(symbol)
        return symbol
            else: 
            return None

So if the function was instructed to find '.' then it should return (0,0) since it is in the first position of the first list. If the function was told to find 'h' then it should return (1,4) since it is in the 4th position (python starts from 0) of the second list. My current code doesn't look for the character closest to the top left as I'm not sure how to program that. Thanks in advance for any help I receive.


Solution

  • Daniel's way is a bit faster in time execution but this also works for comparison:

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