-1

Imagine the list [[0, 1],[2, 3][4, 5]],

how can I get the index of the list [2,3] (which is supposed to be 1), by knowing the number 2. In code something like:

in a list of lists, find the index of the list where list[0] == 2.

This should return 1.

Liweinator
  • 57
  • 7
  • 1
    `next(index for index, l in enumerate(lists) if l[0] == 2)` – Paul M. Oct 16 '20 at 13:23
  • 2
    And that is a very poorly chosen data storage paradigm. It's very inneficient to find this information due to the form of the data container. Maybe try to rethink how you want to store the information based on how you are going to access it. – Mathieu Oct 16 '20 at 13:24

7 Answers7

1

You can do this using a for loop. So for example:

nums = [[0, 1],[2, 3],[4, 5]]

for index, num_list in enumerate(nums):
   if num_list[0] == 2:
      print(index)
abhigyanj
  • 2,355
  • 2
  • 9
  • 29
1

You could use the next function on an enumeration of the list that would return the index of matching items

aList =  [[0, 1],[2, 3],[4, 5]]

index = next(i for i,s in enumerate(aList) if s[0]==2)

print(index) # 1

or, if you're not concerned with performance, using a more compact way by building a list of the first elements of each sublist and using the index() method on that:

index = [*zip(*aList)][0].index(2)

or

index = [i for i,*_ in aList].index(2)
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

Iterate through the list and check the value of the first element. Use a variable to track which index you're looking at.

Tyler
  • 143
  • 9
0
for i in list:
    if i[0]==2:
        print(list.index(i))

Check Kaggle python course for such practical exercises https://www.kaggle.com/learn/python

Gvantsa
  • 69
  • 6
0

Since index method only supports exact value comparison, you need to iterate. See this question: Python: return the index of the first element of a list which makes a passed function true

0
array  = [[0, 1],[2, 3],[4, 5]] 

def get_index(array):
  i = 0

  for element in array:
    if(element[0]==2):
      break
    i+=1

  return i 

print(str(get_index(array)))
erwanlfrt
  • 111
  • 11
0

If you have lots of such queries to make, it might be more efficient to build a dict first, with the first value of each sublist as key and the sublist as value:

data =  [[0, 1], [2, 3], [4, 5]]

data_by_first_value = {lst[0]: lst for lst in data}

This dict will look like:

print(data_by_first_value)
# {0: [0, 1], 2: [2, 3], 4: [4, 5]}

It is then an O(1) operation to get the sublist you're looking for:

print(data_by_first_value[2])
# [2, 3]
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50