Python Forum
Find index value in List - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Find index value in List (/thread-26754.html)



Find index value in List - Martin2998 - May-12-2020

hi,

is there any good ways to find the location of a value in a list that consist of multiple brackets?

so for example:
test = ["54", "cat", "99", "1238"], ["758", "tre", "1233124"], ["hva skjer", "15684", "0"]
print(test.index("758")
gives the error:
print(test.index("cat"))
ValueError: tuple.index(x): x not in tuple
[Finished in 0.2s with exit code 1]


RE: Find index value in List - anbu23 - May-12-2020

>>> [item.index('cat') for item in test if 'cat' in item]
[1]
>>> [item.index('758') for item in test if '758' in item]
[0]



RE: Find index value in List - DeaD_EyE - May-12-2020

The method index raises a ValueError, if the value does not exist in the list.
In addition, you have a 2d list, where you can't just use the method index.

Before you use the method index, you could look up with the in operator, if the value is in the list.

my_list = [1, 2, 3]
# code
if 2 in my_list:
    print("Index:", my_list.index(2))
But you have a 2d-list. You can nest for-loops, but it's not required in this case.
Loop over the rows and you get the columns.
For each column you look if the value you seek is in the row.
If this is the case, just return the row_idx and col_idx.


test = ["54", "cat", "99", "1238"], ["758", "tre", "1233124"], ["hva skjer", "15684", "0"]


def index2d(matrix, value):
    for row_idx, row in enumerate(matrix):
        if value in row:
            return row_idx, row.index(value)


index2d(test, "99")



RE: Find index value in List - deanhystad - May-12-2020

What is your expected return value for test.index("758")? I'm sure you can write a function that returns the desired value, but what is the desired value in this case? 1? 4? (1, 0)?