Last modified: Jan 10, 2023 By Alexander Williams
count items in list matching criteria or condition in python
in this tutorial we'll learn how to count a list with condition
example 1
in this example we'll count how many Dog in the list
1 2 3 4 5 6 7 8 9 10 11 | #listlist_a=['Dog','Cat','Zebra','Tiger','Dog']#check list_a items if matching "Dog" and count themcount=0foriinlist_a:if"Dog"ini:count+=1#print(count)print(count) |
output
2
examlple 2: using inline for loop
1 2 3 4 5 6 7 8 9 10 11 | #listlist_a=['Dog','Cat','Zebra','Tiger','Dog']#check item in list_a if matching "Dog" and count themcriteria=[iforiinlist_aifi=="Dog"]#countcount=len(count)#printprint(count) |
output
2