How to find position of char in Two-dimensional lists?

Question:

I need to find position of specific char in two-dimensional list

I tired

list=[["a","b","c"],["d","e","f"],["g","h","i"]]
print(list.index("c"))

and

print(list.index[0]("c"))

But it does not work:
print(list.index("c"))
builtins.ValueError: ‘c’ is not in list

Asked By: Dominik

||

Answers:

You could try this way:

Explain: your list is a nested list containing sublists, so you have to go one level deeper to get the value that’s you’re interested.

Note – please avoid using built-in list as your variable name -that’s not a good practice.

# L is your list...
# val = 'c'

for idx, lst in enumerate(L):
    if val in lst:
        print(f' which sub-list: {idx}, the value position: {lst.index(val)}')

# Output:
# which sub-list: 0, the value position: 2

# running with val is `g`
# >>> which sub-list: 2, the value position: 0
Answered By: Daniel Hao

You have to loop over the rows. Then check whether the searched character is in the row before trying to get its index.

for i, row in enumerate(list):
    if 'c' in row:
        print(i, row.index('c'))
Answered By: Barmar

print(list.index("c")) does not work, as list as a list containing lists, not chars. I assume you are looking for coordinates as an answer; something like

for i in range(len(list)):
    for j in range(len(list[i])):
        if (list[i][j] == 'c'):
            print(f"c at list[{i}][{j}]")

will give you that.

As for your second suggestion, you need to call index to list[0], so:

list[0].index('c')
Answered By: Wasnoplus

You could do something like this, code image

def find_char(list, char):
    for i in range(len(list)):
        for j in range(len(list[i])):
            if list[i][j] == char:
               return (i, j)
            return None

       list = [["a","b","c"],["d","e","f"],["g","h","i"]]
       char = "c"
       position = find_char(list, char)
       found = ""
       if position:
          found = list[position[0]][position[1]]
       else:
          print(f"Character {char} not found in list")

       print(found)
Answered By: Anthony Tuccitto
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.