-1

As a continuation for this question, how can I get the index of the sublist which contains the element?

So for example if I have:

a = [[1,2],[3,4],[5,6]]
any(2 in i for i in a)
....

How can I get 0 as a result (Because a[0] contains the number 2)?

Madno
  • 910
  • 2
  • 12
  • 27

2 Answers2

1

Alternatively, you can try this too:

for idx, sublst in enumerate(a):
    if 2 in sublst: 
        print(idx)

Output:

0
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
1

Simple list comprehension which iterates over list with indexes using enumerate() will do the trick:

res = [i for i, el in enumerate(a) if 2 in el]

You can achieve same using regular for loop:

res = []
for i, el in enumerate(a):
    if 2 in el:
        res.append(el)
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35