Skip to main content

Command Palette

Search for a command to run...

DAY 27 of PYTHON top 100 questions : from Basic to Advanced !!

Published
1 min read
DAY 27 of PYTHON top 100 questions : from Basic to Advanced !!
P

Hello, I'm Priya Chakraborty, a dedicated B.Tech student in Electrical Engineering at Siliguri Institute Of Technology. I'm an enthusiastic learner, constantly seeking to expand my skill set and knowledge base. With a solid foundation in programming languages such as C, R, Python, and MySQL, I'm poised to tackle complex technical challenges.

But my passions extend beyond the realm of engineering. I'm also an aspiring content writer, driven by a curiosity to communicate ideas, both technical and non-technical, in a way that captivates and educates.

My journey is defined by a relentless pursuit of self-improvement, coupled with strong communication skills. I believe in the power of continuous learning and the importance of sharing knowledge.

Write a Python program to count the number of occurrences of a given element in a given list.

def count_occurrences(lst, element_to_count):
    count = 0
    for item in lst:
        if item == element_to_count:
            count += 1
    return count


my_list = [1, 2, 3, 4, 2, 2, 5, 2, 6]
element = 2
result = count_occurrences(my_list, element)
print(f"The element {element} appears {result} times in the list.")

Output :


The element 2 appears 4 times in the list.

In this program, we define a function count_occurrences that takes two arguments: lst (the list in which we want to count occurrences) and element_to_count (the element we want to count). We initialize a count variable to 0 and then iterate through the list, incrementing the count each time we find an element that matches the one we're counting. Finally, the function returns the count.


If you are a beginner and want to know more about Python programming, you can read my Basics of Python blogs (From part 1 to part 15).


HAPPY LEARNING !!!

More from this blog

Priya's blog

46 posts

Python Developer@Codeclause Mentee @Trailhead Salesforce Content Executive @GDSC SIT'22-23 Google Women Techmakers Ambassador @Google WTM Coreteam @ GirlScript Kolkata