Home > Back-end >  List: Find the first index and count the occurrence of a specific list in list of lists
List: Find the first index and count the occurrence of a specific list in list of lists

Time:09-23

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

CodePudding user response:

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)

and to make sure the code is scalable, we make sure that no error can be rased:

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

key = ["alpha",'Lsive']

count = location.count(key)
print('count', count)

if count:
    index= location.index(key)
    print('index',index)
  • Related