0

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.

peter554
  • 1,248
  • 1
  • 12
  • 24
Rebecca
  • 1
  • 1
  • 2
    Possible duplicate of [Python: Return 2 ints for index in 2D lists given item](https://stackoverflow.com/questions/5775352/python-return-2-ints-for-index-in-2d-lists-given-item) – wwii Feb 11 '19 at 18:58

4 Answers4

1

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) )
MarkReedZ
  • 1,421
  • 4
  • 10
0

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))
peter554
  • 1,248
  • 1
  • 12
  • 24
0

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.

panktijk
  • 1,574
  • 8
  • 10
0

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]))
kederrac
  • 16,819
  • 6
  • 32
  • 55