Python calculates the number of times an element appears in a list
Define a list and calculate the number of times an element appears in the list.
For example:
enter : lst = [15, 6, 7, 10, 12, 20, 10, 28, 10] x = 10 Output : 3
Example 1
def countX(lst, x): count = 0 for ele in lst: if (ele == x): count = count + 1 return count lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8 print(countX(lst, x))
The output results of the above example are:
5
Example 2
Use the count() method
def countX(lst, x): return (x) lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8 print(countX(lst, x))
The output results of the above example are:
5
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.