Python: Count Occurrences of an Element in a List
-- Learning More Than Just Technology, But Also Dreams!
- Home
- HTML
- JavaScript
- CSS
- Vue
- React
- Python3
- Java
- C
- C++
- C#
- AI
- Go
- SQL
- Linux
- VS Code
- Bootstrap
- Git
- Local Bookmarks
Python 3 Tutorial
Python3 Tutorial Python3 Introduction Python3 Environment Setup Python3 VScode Python3 Basic Syntax Python3 Basic Data Types Python3 Data Type Conversion Python3 Interpreter Python3 Comments Python3 Operators Python3 Numbers Python3 Strings Python3 Lists Python3 Tuples Python3 Dictionaries Python3 Sets Python3 Conditional Statements Python3 Loops Python3 First Program Python3 Comprehensions Python3 Iterators and Generators Python3 with Python3 Functions Python3 lambda (Anonymous Functions) Python Decorators Python3 Data Structures Python3 Modules Python __name__ Python3 Input and Output Python3 File Python3 OS Python3 Errors and Exceptions Python3 Object Oriented Python3 Namespace/Scope Python Virtual Environment Creation Python Type Hints Python3 Standard Library Overview Python3 Examples Python Quiz
Python3 Advanced Tutorial
Python3 Regular Expressions Python3 CGI Programming Python3 MySQL (mysql-connector) Python3 MySQL (PyMySQL) Python3 Network Programming Python3 SMTP Sending Email Python3 Multithreading Python3 XML Processing Python3 JSON Python3 Date and Time Python3 Built-in Functions Python3 MongoDB Python3 urllib Python uWSGI Installation and Configuration Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python Useful Resources Python AI Drawing Python statistics Python hashlib Python Quantitative Python pyecharts Python selenium Python Spider Python Scrapy Python Markdown Python sys Python Pickle Python subprocess Python queue Python StringIO Python logging Python datetime Python re Python csv Python threading Python asyncio Python PyQt Python for Loop Python while Loop
Python3 Standard Library Overview
Deep Dive
Web Design and Development
Programming
Programming Languages
Scripting Languages
Web Service
Scripts
Computer Science
Software
Web Services
Development Tools
Python3.x Python: Count Occurrences of an Element in a List
Define a list and count the number of times a specific element appears in the list.
For example:
Input: 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 of the above example is:
5
Example 2: Using the count() Method
def countX(lst, x):
return lst.count(x)
lst =[8,6,8,10,8,20,10,8,8]
x =8
print(countX(lst, x))
The output of the above example is:
5
YouTip