count each element occurrence in list python code example
Example 1: python count repeated elements in a list
# Basic syntax:
dict_of_counts = {item:your_list.count(item) for item in your_list}
# Example usage:
your_list = ["a", "b", "a", "c", "c", "a", "c"]
dict_of_counts = {item:your_list.count(item) for item in your_list}
print(dict_of_counts)
--> {'a': 3, 'b': 1, 'c': 3}
Example 2: count occurrence in array python
arr = np.array( [1, 2, 3, 2, 1, 2])
occ = np.count_nonzero(arr==0)
print(occ)
0
occ = np.count_nonzero(arr==1)
print(occ)
2
Example 3: python count occurrences of an item in a list
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
Example 4: count the number of times a value appears in python
The count of i is: 2
The count of p is: 0