1

Learning Python and tasked with returning the index location of the first letter in the lists. But it has to be to the left uppermost part on any given list. For example 'a' would return as index (0,2).

When I run my code though, it says the letter isn't found. Assuming Value represents the letters and '.' is already defined in the tester. It should return none if its a '.'

area1 = [['.', 'a', 'a', 'D', 'D'], 
         ['.', '.', 'a', '.', '.'], 
         ['A', 'A', '.', 'z', '.'], 
         ['.', '.', '.', 'z', '.'], 
         ['.', '.', 'C', 'C', 'C']]
def find_spot_values(value,area):
    for row in area:# Looks at rows in order
        for letter in row:# Looks at letter strings
            if value == letter in area: #If strings are equal to one another
                area.index(value)# Identifies index?
find_spot_values('D',area1)

3 Answers 3

1

With minimal changes to your code

def find_spot_values(value, area):
    for row in area:  # Looks at rows in order
        for letter in row:  # Looks at letter strings
            if value == letter:  # If strings are equal to one another
                return area.index(row), row.index(letter)  # Identifies indices
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the simple explanation, also Is there a way to reverse this and pick the latest string in the list?
1

I think you want something like this:

def find_spot_values(value,area):
  for row_idx, row in enumerate(area):
      if value in row:
          return (row_idx, row.index(value))

Comments

1

I modified you function slighly, now it works:

area1 = [['.',  'a',    'a',    'D',    'D'], ['.', '.',    'a',    '.',    '.'], ['A', 'A',    '.',    'z',    '.'], ['.', '.',    '.',    'z',    '.'], ['.', '.',    'C',    'C',    'C']]
def find_spot_values(value,area):
    # Loop through the rows, id_row contains the index and row the list
    for id_row, row in enumerate(area):# Looks at rows in order
        # Loop through all elements of the inner list
        for idx, letter in enumerate(row):
            if value == letter: #If strings are equal to one another
                return (id_row, idx)
    # We returned nothing yet --> the letter isn't in the lists
    return None
print(find_spot_values('D',area1))

This returns a tuple with the 'coordinates' or None, if the value isn't in area.

In the inner loop you could use the index() function as well. In that case you would have to deal with exceptions if the list doesn't contain the letter.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.