Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading