'Python find index of list of list, but only at specific index of internal list
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
Solution 1:[1]
use isinstance:
for item in my_list:
if isinstance(item[0], str):
print("True!")
my_list since you should not name your lists list.
Solution 2:[2]
Two possible solutions:
- 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]
- If you want a boolean output list:
ans = [True if type(i[0]) == str else False for i in list]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Damiaan |
| Solution 2 | Anshumaan Mishra |
