Skip to content
Advertisement

How to extract a sublist by the value of the first element from a nested list

I want to extract a sublist from a nested list based on the first element in each list. I have the following nested list:

input = [
    ['nom', 'N', 'eye'],
    ['acc', 'E', 'computer'],
    ['dat', 'C', 'screen']
    ]

I want to have a function which returns ['nom', 'N', 'eye'] when the first element of the sublist 'nom' is inputted, for instance:

output = ['nom', 'N', 'eye'] # When the function takes 'nom' as its argument
output = ['acc', 'E', 'computer'] # When the function takes 'acc' as its argument
output = ['dat', 'C', 'screen'] # When the function takes 'dat' as its argument  

How should I achieve this with python3.6+?

Advertisement

Answer

my_list = [
    ['nom', 'N', 'eye'],
    ['acc', 'E', 'computer'],
    ['dat', 'C', 'screen']
]
my_input = input("Enter first string to find: ")

for lis in my_list:
    if lis[0] == my_input:
        print(lis)
        break

Output:

Enter variable name: nom
['nom', 'N', 'eye']
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement