How to count the occurrences of all items of list in a tuple with Python

2 Answers

0 votes
def count_occurrences(tpl, lst): 
    count = 0
    for item in tpl: 
        if item in lst: 
            count += 1
      
    return count  


tpl = (1, 2, 4, 3, 2, 1, 1, 1, 5, 6, 7, 2, 8, 9, 9) 
lst = [1, 2] 
print(count_occurrences(tpl, lst)) 



'''
run:

7

'''

 



answered Dec 19, 2019 by avibootz
0 votes
def count_occurrences(tpl, lst): 
    st = set(lst) 
    return sum(1 for n in tpl if n in st) 


tpl = (1, 2, 4, 3, 2, 1, 1, 1, 5, 6, 7, 2, 8, 9, 9) 
lst = [1, 2] 
print(count_occurrences(tpl, lst)) 



'''
run:

7

'''

 



answered Dec 19, 2019 by avibootz

Related questions

1 answer 176 views
1 answer 171 views
1 answer 182 views
2 answers 194 views
...