Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python List methods
Next article icon

Thecount() method is used to find the number of times a specific element occurs in a list. It is very useful in scenarios where we need to perform frequency analysis on the data.

Let's look at a basic example of thecount() method.

Python
a=[1,2,3,1,2,1,4]c=a.count(1)print(c)

Output
3

Explanation:a.count(1) counts the occurrences of1 in the list, as it is occurring 3 times in the list so the output is 3.

Syntax

list_name.count(value)

Prameters:

  • list_name:The list object where we want to count an element.
  • value:The element whose occurrences need to be counted.

Return Type: it anintegervalue, which represents the number of times the specified element appears in the list.

Examples of count() method

Example 1: Lits Containing Different Datatypes

The count() method also works well with list that have different types of data.

Python
a=[1,'GfG',3.14,'GfG',1,True]c1=a.count('GfG')c2=a.count(1)print(c1)print(c2)

Output
23

Explanation:

  • 'GfG' appears twice.
  • 1 appearstwiceexplicitly, but True is also counted because True == 1 inPython, making the total countthree.

Example 2: Count occurrence of sub-list in list of Lists

Thecount() method does not search within nested lists and it will only count occurrences at the top level.

Python
a=[1,[2,3],1,[2,3],1]c=a.count([2,3])print(c)

Output
2

Explanation: Thesublist [2, 3] is treated as a single element in the list. The count()method counts it twice because it appears twice as a nested list.

Example 3: Counting Word Frequency in a List

This example simulates word analysis in a sentence by counting how often a word appears.

Python
s="python is easy to learn and python is powerful".split()c1=s.count("python")c2=s.count("is")print(c1)print(c2)

Output
count of python:  2count of is:  2

Explanation:

  • .split() method splits the string into a list of words.
  • We usecount()to check how many times "python" and "is" appear.

Related articles:


Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp