How to know the index of an element in a list

Question:

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

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
Asked By: user20647609

||

Answers:

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')
Answered By: xingyu xia

More simpler way you can use any()

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

for i, v in enumerate(s):
    if any('a' in x for x in v):
        print(i)

Gives #

0
Answered By: Bhargav
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.