Home > Blockchain >  Python find index of list of list, but only at specific index of internal list
Python find index of list of list, but only at specific index of internal list

Time:03-26

I have a list of lists in the format:

list = [["5:2", "1:0"],["3:4", "5:2"],["1:2", "1:1"],["4:5", "1:0"]]

I would like to check if the first index of each internal lists contains a string. I have tried to use the following:

(next(i for i,j in enumerate(list) if (a) in j))

However, this checks every string in the list of lists, instead of a specific index.

How could I modify this code to only check index 0 of the internal list?

Thanks

CodePudding user response:

use isinstance:

for item in my_list:
    if isinstance(item[0], str):
        print("True!")

my_list since you should not name your lists list.

CodePudding user response:

Two possible solutions:

  1. If you want all the list elements' indices that have the first element as a string:
ans = [i for i, j in enumerate(list) if type(j[0]) == str]
  1. If you want a boolean output list:
ans = [True if type(i[0]) == str else False for i in list]
  • Related