Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Find index value in List

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"]
gives the error:
ValueError: tuple.index(x): x not in tuple
[Finished in 0.2s with exit code 1]
>>> [item.index('cat') for item in test if 'cat' in item]
>>> [item.index('758') for item in test if '758' in item]
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")
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die:
All humans together. We don't need politicians!
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)?

Possibly Related Threads…
Thread Author Replies Views Last Post
  Find Common Elements in 2 list quest 4 245 Apr-14-2021, 03:57 PM
Last Post: quest
  IndexError: list index out of range brunolelli 11 516 Mar-25-2021, 11:36 PM
Last Post: brunolelli
  Changing Index of 2 List in python giddyhead 0 212 Mar-05-2021, 05:45 PM
Last Post: giddyhead
  IndexError: list index out of range ramu4651 2 408 Jan-24-2021, 01:45 PM
Last Post: buran
  List of error codes to find (and count) in all files in a directory tester_V 8 582 Dec-11-2020, 07:07 PM
Last Post: tester_V
  Find _ in a list 1234 15 922 Dec-01-2020, 07:53 PM
Last Post: bowlofred
Question Matching variable to a list index Gilush 17 827 Nov-30-2020, 01:06 AM
Last Post: Larz60+
  How to get index of minimum element between 3 & 8 in list Mekala 2 375 Nov-10-2020, 12:56 PM
Last Post: DeaD_EyE
  List index out of range error while accessing 2 lists in python K11 2 494 Sep-29-2020, 05:24 AM
Last Post: K11
  str.find() not returning correct index. DreamingInsanity 10 978 Aug-18-2020, 05:41 PM
Last Post: DreamingInsanity

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020