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 know the index of an element in a list

If I have a list like


[[a, b], [c, d], [e, f]]

How would I know that element a is in index 0 of the big list. I’m unsure on how to do this with a 2 dimensional array.

I tried to use index, but it not works

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

s = [['a', 'b'], ['c', 'd'], ['e', 'f']]

s.index('a')
Traceback (most recent call last):
  File "C:/Users/xxy/PycharmProjects/tb/test.py", line 3, in <module>
    s.index('a')
ValueError: 'a' is not in list

>Solution :

You can solve it with a loop

s = [['a', 'b'], ['c', 'd'], ['e', 'f']]
x = 'a'
find = False
for i, line in enumerate(s):
    if x in line:
        print(f'find {x} at', i, line.index(x))
        find = True
        break
if not find:
    print(f'{x} is not in list')
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