Search code examples
pythonlistindexingsublist

How to Find the Index of an Item in a sublist of a list (python)


ExampleList = [['Ck'], ['Kat'], ['Arcadiusz']]

ExampleListFull = [['CK', 21, 'Male'], ['Kat', 19, 'Female'], ['Arcadiusz', 30, 'Male']]
           

User = str(input())
User = User.capitalise()

if ([User] in ExampleList) == True:

From here we want to find the Index of "User", lets go with Kat, I know it's 1, 0,
However I want the program to be able to tell me for what ever name is entered, this way I than can print
(User + '\'s', 'age is', (ExampleListFull(variable) (variable)))


Solution

  • ExampleListFull = [['CK', 21, 'Male'], ['Kat', 19, 'Female'], ['Arcadiusz', 30, 'Male']]
    User = str(input())
    User = User.capitalise()
    

    Here, we create a dummy list with the values of all the names. This should print ['CK', 'Kat', 'Arcadiusz']

    names = [value[0] for value in data]
    print(names)
    

    The one-line for-loop is the equivalent of doing:

    names = []
    for value in data:
        names.append(value[0])
    

    Then we can print the result

    print(names.index(name))
    print("Age is", {data[names.index(name)][1]})
    

    This can all be shortened to just a few lines of code like this:

    data = [['CK', 21, 'Male'], ['Kat', 19, 'Female'], ['Arcadiusz', 30, 'Male']]
    
    User = str(input())
    User = User.capitalise()
    
    age = data[[value[0] for value in data].index(name)][1]
    # gender= data[[value[0] for value in data].index(name)][2]