Rebecca
Rebecca

Reputation: 1

Find the index of a value in a 2D array

Here is my code:

test_list= [
    ["Romeo and Juliet","Shakespeare"],
    ["Othello","Play"],
    ["Macbeth","Tragedy"]
]

value = "Tragedy"

print(test_list.index(value))

As a result I get “ValueError: ‘Tragedy’ is not in list

I’d come to the conclusion that .index only works for 1D arrays? But then how do I do it die 2D arrays? This code works fine if I make the array 1D. Please help, but in simple terms as I am a beginner.

Apologies for formatting issues on mobile. The array is set out correctly for me.

Upvotes: 0

Views: 2919

Answers (4)

kederrac
kederrac

Reputation: 17322

numpy arrays may help in your specific case

import numpy

test_array = numpy.array(Testlist)
value = "Tragedy"

numpy.where(test_array==value)
# you will get (array([2]), array([1]))

Upvotes: 0

panktijk
panktijk

Reputation: 1614

You can also use numpy:

import numpy as np
test_list = np.array(test_list)
value = 'Tragedy'
print(np.where(test_list == value))

Output:

(array([2]), array([1]))

If you have multiple occurences of an element, then np.where will give you a list of indices for all the occurences.

Upvotes: 0

peter554
peter554

Reputation: 1378

You can also use the map operator:

# Get a boolean array - true if sublist contained the lookup value
value_in_sublist = map(lambda x: value in x, test_list)

# Get the index of the first True
print(value_in_sublist.index(True))

Upvotes: 0

MarkReedZ
MarkReedZ

Reputation: 1437

Loop through your list and search each sublist for the string.

Testlist = [
               ["Romeo and Juliet","Shakespeare"],
               ["Othello","Play"],
               ["Macbeth","Tragedy"]
               ]

Value = "Tragedy"

for index, lst in enumerate(Testlist):
  if Value in lst:
    print( index, lst.index(Value) )

Upvotes: 1

Related Questions