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 | #list list_a = ['Dog', 'Cat', 'Zebra', 'Tiger', 'Dog'] #check list_a items if matching "Dog" and count them count = 0 for i in list_a: if "Dog" in i: 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 | #list list_a = ['Dog', 'Cat', 'Zebra', 'Tiger', 'Dog'] #check item in list_a if matching "Dog" and count them criteria = [i for i in list_a if i == "Dog"] #count count = len(count) #print print(count) |
output
2