5

I am trying to get the index of an element in nested lists in python - for example [[a, b, c], [d, e, f], [g,h]] (not all lists are the same size). I have tried using

strand_value= [x[0] for x in np.where(min_value_of_non_empty_strands=="a")]

but this is only returning an empty list, even though the element is present. Any idea what I'm doing wrong?

7
  • what is the expected output? Commented Nov 26, 2015 at 12:21
  • In this instance, 0, I would then try using x[1] to get 0 again - I want to know which list it's in and which position within the list Commented Nov 26, 2015 at 12:24
  • should it not be 0 0 since you are looking for a Commented Nov 26, 2015 at 12:25
  • I am trying to find the index of any given string, for which I do not know its position or which list it is in - if I can get 0 0 straight away, I would find that very helpful Commented Nov 26, 2015 at 12:27
  • If you have a list of strings, then it is much easier to solve than a list of lists of stings. Commented Nov 26, 2015 at 12:31

8 Answers 8

10
def find_in_list_of_list(mylist, char):
    for sub_list in mylist:
        if char in sub_list:
            return (mylist.index(sub_list), sub_list.index(char))
    raise ValueError("'{char}' is not in list".format(char = char))

example_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]

find_in_list_of_list(example_list, 'b')
(0, 1)
Sign up to request clarification or add additional context in comments.

2 Comments

This is O(N^2) and will be slow if mylist is long.
A more general solution would be better for a problem like this. Check out My answer.
3

You could do this using List comprehension and enumerate

Code:

lst=[["a", "b", "c"], ["d", "e", "f"], ["g","h"]]
check="a"
print ["{} {}".format(index1,index2) for index1,value1 in enumerate(lst) for index2,value2 in enumerate(value1) if value2==check]

Output:

['0 0']

Steps:

  • I have enumerated through the List of List and got it's index and list
  • Then I have enumerated over the gotten list and checked if it matches the check variable and written it to list if so

This gives all possible output

i.e.)

Code2:

lst=[["a", "b", "c","a"], ["d", "e", "f"], ["g","h"]]
check="a"
print ["{} {}".format(index1,index2) for index1,value1 in enumerate(lst) for index2,value2 in enumerate(value1) if value2==check]

Gives:

['0 0', '0 3']

Notes:

  • You can easily turn this into list of list instead of string if you want

Comments

2

suppose your list is like this:

lst = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g','h']]
list_no = 0
pos = 0
for x in range(0,len(lst)):
    try:
        pos = lst[x].index('e')
        break
    except:
        pass

list_no = x

list_no gives the list number and pos gives the position in that list

Comments

0

does this suffice?

array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
for subarray in array:
    if 'a' in subarray:
        print(array.index(subarray), '-', subarray.index('a'))

This will return 0 - 0. First zero is the index of the subarray inside array, and the last zero is the 'a' index inside subarray.

Comments

0

Reworked Bhrigu Srivastava's proposal:

def findinlst(lst, val):
    for x in range(0, len(lst)):
        try:
            pos = lst[x].index(val)
            return [x, pos]
        except:
            continue
    return [False, False]  # whatever one wants to get if value not found

arr = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]

findinlst(arr, 'b')
[0, 1]

findInLst(arr, 'g')
[2, 0]

findinlst(arr, 'w')
[False, False]

Comments

0

You can implement your own findIndex function, this looks like Javascipt's Array.prototype.findIndex

def findIndex(callback, list):
    for index, element in enumerate(list):
        if callback(element):
            return index
    return -1

Comments

0

A little bit of "amateur" approach and yet very easy to understand:

Creating a flag boolean value that will execute the result based on if it is True or False with a nested for loop.

entry=input()
listtt=[["a","b","c"],["d","e","f"],["g","h"]]
found=False
for sublist in listtt:
    for charr in sublist:
        if entry==charr:
            print(f"'{entry}' found in sublist {listtt.index(sublist)} with index {sublist.index(charr)}")
            found=True
            break
if found==False:
    print(f"'{entry}' not found")

Comments

0

Expanding on DainDwarf's answer, this will return multiple values if the searched item is in more than one of the nested lists:

def find_in_list_of_list(mylist, char):
    found_list = []
    for sub_list in mylist:
        if char in sub_list:
            found_list.append(f'({mylist.index(sub_list)}, {sub_list.index(char)})')
    if len(found_list) > 0:
        return found_list


example_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h'], ['a', 'b', 'c', 'd']]

print(find_in_list_of_list(example_list, 'c'))

I also got en error when changing the search from 'b' to 'x' in Dwarf's code:

Traceback (most recent call last):
  File "C:\main.py", line 9, in <module>
    print(find_in_list_of_list(example_list, 'x'))
  File "C:\main.py", line 5, in find_in_list_of_list
    raise ValueError("'{char}' is not in list".format(char = char))
ValueError: 'x' is not in list

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.