Write a Python program to count the frequency of a given element?
**Introduction**
Python is a high-level, interpreted programming language that is widely used for multiple purposes such as web development, scientific computing, data analysis, and artificial intelligence, among others. One of the most common tasks in programming is counting the frequency of a given element in a list. In this guide, we will learn how to write a Python program to count the frequency of a given element.
**Problem Statement**
Given a list of elements and a specific element, count the frequency of the given element in the list.
**Approach**
We can use a for loop to iterate through the list and count the frequency of the given element. We can use a counter variable to keep track of the frequency.
**Code**
```python
def count_frequency(lst, element):
count = 0
for item in lst:
if item == element:
count += 1
return count
```
**Explanation**
The above code defines a function called `count_frequency` that takes two arguments, `lst` and `element`. `lst` is the list of elements and `element` is the specific element whose frequency we want to count.
We initialize a counter variable called `count` to 0. We then use a for loop to iterate through each item in the list. If the item is equal to the given element, we increment the counter variable by 1. Finally, we return the value of the counter variable.
**Example**
Let's say we have a list of numbers `[1, 2, 3, 4, 5, 2, 2, 4]`. We want to count the frequency of the element `2`. We can call the function like this:
```python
freq = count_frequency([1, 2, 3, 4, 5, 2, 2, 4], 2)
print(freq)
```
The output will be `3`, which is the frequency of the element `2` in the list.
**Conclusion**
In this guide, we learned how to write a Python program to count the frequency of a given element in a list. We used a for loop to iterate through the list and a counter variable to keep track of the frequency. We also provided an example to demonstrate the usage of the function.
Write a Python program to count the frequency of a given element?
# Python program to count the frequency of a given element
# entering a list from user
list1=eval(input("Enter a list of numbers:"))
length=len (list1)
# estimating the count of the number be 0
count=0
# finding frequency of the given element
for i in range(0, length) :
num=int (input (" enter the number for which frequency is required:"))
if num==list1[i]
count=+1
print( "frequency of the given number is:"count)
To make sure you are not studying endlessly, EduRev has designed Class 10 study material, with Structured Courses, Videos, & Test Series. Plus get personalized analysis, doubt solving and improvement plans to achieve a great score in Class 10.