1

p = [['a','b','c'],['x','y','z']]

How can I get the list index containing the string(char) 'a'?

'a' in list doesn't work, or at least I can't figure it out.

3
  • 3
    You have list inside a list. Which list's index do you want? Commented Nov 27, 2018 at 12:45
  • print([i for i, v in enumerate(p) if "a" in v]) ? Commented Nov 27, 2018 at 12:47
  • 1
    can the nesting be arbitrary and not fixed to depth=2? Commented Nov 27, 2018 at 12:50

3 Answers 3

1

use in but in the sublists, not in the global list of lists. Combined with enumerate to get the index of the matching list(s)

p = [['a','b','c'],['x','y','z']]

idx = [i for i,sublist in enumerate(p) if 'a' in sublist]

that gives you a list of indexes. Here we have only one element:

>>> idx
[0]

You can use the same technique to compute the index of a in the sublist BTW (with idx = [i for i,sublist in enumerate(p) if 'a' in sublist])

To get a sole value or None, just iterate once on a generator comprehension:

idx = next((i for i,sublist in enumerate(p) if 'a' in sublist),None)
Sign up to request clarification or add additional context in comments.

Comments

0

If you set the maximum nesting depth to 2 you can use the following code to get both indices.

p = [['a','b','c'],['x','y','z']]

def get_indices(p, search_for='a'):
    return [(i, sublist.index(search_for)) for i,sublist in enumerate(p) if search_for in sublist]

print('a', get_indices(p, search_for='a'))
print('b', get_indices(p, search_for='b'))
print('c', get_indices(p, search_for='c'))
print('x', get_indices(p, search_for='x'))
print('y', get_indices(p, search_for='y'))
print('z', get_indices(p, search_for='z'))
print('k', get_indices(p, search_for='k'))

output:

a [(0, 0)]
b [(0, 1)]
c [(0, 2)]
x [(1, 0)]
y [(1, 1)]
z [(1, 2)]
k []

Comments

0

Try this:

list_count = 0
for x in list:
   list_count += 1
   if 'a' in x:
       print ("Index in sublist" %(x.index('a')))
       print("Index of outer list" %(list_count))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.