Search code examples
pythonpython-3.xlistlist-comprehension

List: Find the first index and count the occurrence of a specific list in list of lists


we have a variable named location.

location=[["world", 'Live'], ["alpha",'Live'], ['hello', 'Scheduled'],['alpha', 'Live'], ['just', 'Live'], ['alpha','Scheduled'], ['alpha', 'Live']]

i want to find the first index and count occurrence of list["alpha",'Live'] in location. i tried the following:

index= [location.index(i) for i in location if i ==["alpha", 'Live'] ]
count = [location.count(i) for i in location if i ==["alpha",'Live'] ]
print('index',index)
print('count', count)

this returns: index [1, 1, 1] count [3, 3, 3]

but is there a way to find both first index, count simultaneously using list comprehension.

expected output:

index, count = 1, 3


Solution

  • does this solve you problem?

    location=[["world", 'Live'], ["alpha",'Live'], ['hello', 'Scheduled'],['alpha', 'Live'], ['just', 'Live'], ['alpha','Scheduled'], ['alpha', 'Live']]
    index= location.index(["alpha",'Live'])
    count = location.count(["alpha",'Live'])
    print('index',index)
    print('count', count)
    

    if ['alpha','live'] is not found, find the first ['alpha',??] and print its index and count.

    location = [["world", 'Live'], ["alpha", 'Live'], ['hello', 'Scheduled'], [
        'alpha', 'Live'], ['just', 'Live'], ['alpha', 'Scheduled'], ['alpha', 'Live']]
    
    key = ["alpha", 'Lsive']
    
    count = location.count(key)
    
    if count:
        index = location.index(key)
        print('count', count)
        print('index', index)
    else:
        for i in location:
            if i[0] == key[0]:
                key = i
                count = location.count(key)
                index = location.index(key)
                print('count', count)
                print('index', index)
        else:
            print('not found')
    

    cleaner code by @yadavender yadav

    location = [["alpha", 'Scheduled'], ["alpha", 'Live'], ['hello', 'Scheduled'], [
        'alpha', 'Live'], ['just', 'Live'], ['alpha', 'Scheduled'], ['alpha', 'Live']]
    
    key = ["alpha", 'Scheduled']
    
    count = location.count(key)
    
    if count:
        index = location.index(key)
    else:
        index=[location.index(i) for i in location if i[0]=="alpha"][0]
    print('count', count)
    print('index', index)