The Wayback Machine - https://web.archive.org/web/20241008202230/https://www.geeksforgeeks.org/python-list-count-method/
Open In App

Python List count() method

Last Updated : 20 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python List count() method returns the count of the occurrences of a given element in a list.

Example:

Python3




#create a list
fruits = ["Apple", "Mango", "Banana", "Cherry" , "Papaya"]
# printing count using count() function
print(fruits.count("Apple"))


Output

1

What is the list count() Method?

list count() function in Python is a built-in function that lets you count the occurrence of an element in a list. It returns the count of how many times an element is present in a list.

It has various applications depending on how you use it. For example: If the count of any element is greater than 1 that means there are duplicate values. If count is 0 that means the element is not present in the list. So depending on how you use it, it can have different uses.

It only accepts one parameter, if you pass more than one parameter it raises TypeError.

List count() Method Syntax

list_name.count(object) 

Parameters: 

  • object: is the item whose count is to be returned.

Returns:  

Returns the count of how many times an object occurs in the list. 

How to Use List count() Function

The list count() function is a very easy-to-use function, you just need to call the count() function with the object list and pass the element as a parameter in the function. 

Let’s understand better how to count the occurrence of an element in the list with a simple example:

Python3




#creating a list
Rand = [1,3,2,4,1,3,2,4,5,2,3]
#lets count occurence of 2
print(Rand.count(2))


Output

3

More Examples on List count() Method

Let’s discuss some of the examples in different use-cases of count() method.

Example:

Python3




list2 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b']
print(list2.count('b'))


Output

3

Count Tuple and List Elements Inside the List

Count occurrences of List and Python Tuples inside a list using the Python count() method.

Python3




list1 = [ ('Cat', 'Bat'), ('Sat', 'Cat'), ('Cat', 'Bat'),
          ('Cat', 'Bat', 'Sat'), [1, 2], [1, 2, 3], [1, 2] ]
 
# Counts the number of times 'Cat' appears in list1
print(list1.count(('Cat', 'Bat')))
 
# Count the number of times sublist
# '[1, 2]' appears in list1
print(list1.count([1, 2]))


Output

2
2

Exceptions While Using Python list count() method

Let’s also discuss some errors you might face while using the count() function.

TypeError: count() takes exactly one argument

List count() in Python raises TypeError when more than 1 parameter is passed.

Python3




list1 = [1, 1, 1, 2, 3, 2, 1]
 
# Error when two parameters is passed.
print(list1.count(1, 2))


Output:

Traceback (most recent call last):
File "/home/41d2d7646b4b549b399b0dfe29e38c53.py", line 7, in
print(list1.count(1, 2))
TypeError: count() takes exactly one argument (2 given)

Practical Application

 Let’s say we want to count each element in a Python list and store it in another list or say Python dictionary.

Python3




# Python3 program to count the number of times
# an object appears in a list using count() method
 
lst = ['Cat', 'Bat', 'Sat', 'Cat', 'Mat', 'Cat', 'Sat']
 
# To get the number of occurrences
# of each item in a list
print ([ [l, lst.count(l)] for l in set(lst)])
 
# To get the number of occurrences
# of each item in a dictionary
print (dict( (l, lst.count(l) ) for l in set(lst)))


Output

[['Mat', 1], ['Sat', 2], ['Bat', 1], ['Cat', 3]]
{'Mat': 1, 'Sat': 2, 'Bat': 1, 'Cat': 3}

We covered the definition, syntax, and examples of the list count() method. We also discussed different exceptions and practical examples of the function.

The list count() method is a very basic function of list operations and it is very easy to use.

Read More: Python List Methods

Also Read:



Previous Article
Next Article

Similar Reads

Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Count set bits using Python List comprehension
Write an efficient program to count number of 1s in binary representation of an integer. Examples: Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 11 Output : 3 Binary representation of 11 is 1101 and has 3 set bits We have existing solution for this problem please refer Count set bits in an integer link. W
2 min read
Python | Count the elements in a list until an element is a Tuple
In this problem, we need to accept a list. The list can have nested tuples. We need to count the elements in a list until a tuple has been encountered. Examples: Input : [4, 5, 6, 10, (1, 2, 3), 11, 2, 4] Output : 4 Input : [4, (5, 6), 10, (1, 2, 3), 11, 2, 4] Output : 1 Method #1: In this program we will use the concept of isinstance() to verify w
2 min read
Python | Count number of items in a dictionary value that is a list
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a key is a list. To check that the value is a list or
5 min read
Python | Find all elements count in list
Getting the length of list is quite common problem and has been dealt with and discussed many times, but sometimes, we require to better it and find total number of elements, i.e. including those of nested list as well. Let's try and get the total count and solve this particular problem. Method #1: Using list comprehension + len() We can solve this
6 min read
Count dictionaries in a list in Python
A list in Python may have items of different types. Sometimes, while working with data, we can have a problem in which we need to find the count of dictionaries in particular list. This can have application in data domains including web development and Machine Learning. Lets discuss certain ways in which this task can be performed. Input : test_lis
5 min read
Count the Number of Null Elements in a List in Python
In data analysis and data processing, It's important to know about Counting the Number of Null Elements. In this article, we'll explore how to count null elements in a list in Python, along with three simple examples to illustrate the concept. Count the Number of Null Elements in a List in PythonIn Python, the None keyword is used to represent the
3 min read
Python | Count occurrences of an element in a list
Given a list in Python and a number x, count the number of occurrences of x in the given list. Examples: Input: lst = [15, 6, 7, 10, 12, 20, 10, 28, 10], x = 10Output: 3 Explanation: 10 appears three times in given list.Input: lst = [8, 6, 8, 10, 8, 20, 10, 8, 8], x = 16Output: 0Explanation: 16 appears zero times in given list.Count Occurrences of
6 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python List Comprehension | Segregate 0's and 1's in an array list
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Examples: Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python usi
2 min read
Python | Sort list of list by specified index
We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
8 min read
Python | Remove all values from a list present in other list
Sometimes we need to perform the operation of removing all the items from the lists that are present in another list, i.e we are given some of the invalid numbers in one list which need to be get ridden from the original list. Let's discuss various ways How to remove the elements of a list from another list in Python. Illustration: Input: List one
10 min read
Python | Sort list according to other list order
Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let's discuss certain ways to sort list according to other list order. Method #1 : Using List
5 min read
Python | Ways to Convert a 3D list into a 2D list
List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development. Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or while contributing to open source. Below are some w
3 min read
Python | Merge List with common elements in a List of Lists
Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions. Below are some ways to achieve this. Input: [[11, 27, 13], [11, 27, 55], [22, 0, 43], [22, 0, 96], [13, 27, 11], [13, 27, 55], [43, 0, 22], [43, 0, 96], [55, 27, 11]] Out
3 min read
Python | Subtract two list elements if element in first list is greater
Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.Examples: Input: l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] Output: [10, 20, 30, 10, 30, 50] Input: l1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] l2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output: [6, 5,
5 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Appending Item to Lists of list using List Comprehension | Python
If you are a Python user, you would know that in Python, we can use the append() method to add an item to an existing list. This list may already contain other items or be empty. Further, the item to be added can simply be a number a character, or even an entire tuple or list. However, if you are trying to append an item to lists within a list comp
5 min read
Python | sympy.count() method
Using the count() method in the sympy module, we can count the number of variables used in the mathematical function. count() method returns the number of variables used in the mathematical function. Syntax : sympy.count(x) Return : the count of variables. Code #1: With the help of the below examples, we can clearly understand that using sympy.coun
1 min read
Python String count() Method
Python String count() function returns the number of occurrences of a substring within a String. C/C++ Code #initializing a string my_string = "Apple" #using string count() method char_count = my_string.count('A') #printing the result print(char_count) Output1 In this article, we will explore the details of the count() method, exploring i
4 min read
cmp(list) method in Python
cmp(list) is a method specified in Number in Python 2. The comparison of integral numbers have been discussed using cmp(). But many a times, there is a need to compare the entire list that can be composed of similar or different data types. In this case, different case scenarios occur and having knowledge of them can at times prove to be quite hand
4 min read
Use get() method to create a dictionary in Python from a list of elements
Prerequisites: Get() method for dictionaries in Python The naive approach for creating a dictionary from a list of items we can use the for loop. See the below example for better understanding. Example: li =['a', 'b', 'c', 'a', 'd', 'e', 'b', 'a'] di ={} for ele in li: # Increase the value of key # if exists if ele in di: di[ele]= di[ele]+1 else: #
2 min read
Selecting a drop-down list by using the Selenium.select_by_visible_text() method in Python
Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python. Different methods of Select class: Selection an option from the dropdown menu by INDEX.Sel
2 min read
Python List clear() Method
Python List clear() method removes all items from the List making it an empty/null list. Example C/C++ Code lis.clear() print(lis) Output[] What is List clear() Method?list clear() is an in-built function in Python, that is used to delete every element from a list. It can make any list into a null list and should be used with caution. It is one of
4 min read
Python List remove() Method
Python list remove() method removes a given element from the list. Example: C/C++ Code lis.remove("b") print(lis) Output['a', 'c'] List remove() Syntaxlist_name.remove(obj) Parameterobj: object to be removed from the list ReturnsThe method does not return any value but removes the given object from the list. ExceptionIf the element doesn'
5 min read
Python List append() Method
Python list append() method is used to add elements at the end of the list. Example Python Code list.append(8) print(list) Output [2, 5, 6, 7, 8] Python List Append() SyntaxList_name.append(element) Parameterelement: an element (number, string, list, etc.) to be added at the end of the list. The parameter is mandatory and omitting it can cause an e
3 min read
Python List extend() Method
The Python List extend() method adds items of an iterable (list, tuple, dictionary, etc) at the end of a list. Example C/C++ Code other_cars = ["Maruti", "Tata"] cars.extend(other_cars) print(cars) Output ['Audi', 'BMW', 'Jaguar', 'Maruti', 'Tata']List extend() Syntaxlist_name.extend(iterable) Parameters:iterable: Any iterable (
4 min read
Python List sort() Method
Python list sort() method sorts the elements of a list. It sorts in ascending order by default but can also sort values in descending order or in a custom manner using its parameters. Example: Python list sort alphabetically and numerically. [GFGTABS] Python alphabets = ['a','e','d','c','b'] alphabets.sort()
5 min read
Python List copy() Method
The list Copy() method makes a new shallow copy of a list. Example [GFGTABS] Python # Using list fruits fruits = ["mango","apple","strawberry"] # creating a copy shakes shakes = fruits.copy() # printing shakes list print(shakes) [/GFGTABS]Output['mango', 'apple', 'strawberry'] What is List Copy() Method?The list Copy()
5 min read