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

Time:12-17

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

CodePudding user response:

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'))

CodePudding user response:

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

CodePudding user response:

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')

CodePudding user response:

You could do something like this [enter image description here][1]

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)


  [1]: https://i.stack.imgur.com/iDnI1.png
  • Related