Python list find count

How to count the number of occurrences of a list item in Python

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

Introduction

Python provides us with different ways to count occurrences of list items. While certain ways are faster than others, this shot will provide you with a variety of methods that can be used.

As an exercise, try out all the methods in this shot to find the best method for yourself. Let me know in the comments which one you found to be the fastest!

Note: You can find the execution time of the code in the output once you run the code.

1. Count

count is the easiest to use of all methods. This method expects one argument, i.e., the list element whose number of occurrences are counted.

Читайте также:  Java consumer without params

Syntax

l = ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
print(l.count('a'))
print(l.count('e'))

We can also use this method to get a count of all distinct values at once. For this purpose, we can use list comprehensions.

Comprehensions in Python provide us with a compact and concise way to build new sequences (lists, sets, dictionaries, etc.)

Let’s check out some examples.

l = ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
print([[x,l.count(x)] for x in set(l)])
print(dict((x,l.count(x)) for x in set(l)))

2. Operator

In this type, you have to import the operator module. From this module, we use the countOf method.

This method takes two arguments and returns an integer as an output.

Syntax

l = ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
import operator as op
print(op.countOf(l,'a'))

3. Counter

Here, you have to import the Counter from the collections module. The counter method is a collection where elements are stored as a dictionary with keys and counts as values.

Syntax

Let’s look at an example of this.

l = ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
from collections import Counter
print(Counter(l))
c = Counter(l) # for single element
print(c['a'])

4. pandas

pandas, an open-source data analysis and manipulation tool, is a trendy library. We can also use it to count the number of occurrences of list elements.

We can use the Series.value_counts method from pandas. Since pandas uses series that are one-dimensional arrays with axis labels, we convert our list to series and then use the value_counts method on top of it.

value_counts return the object in descending order. The first element is the most frequently occurring element.

Syntax

import pandas as pd
l = ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
my_count = pd.Series(l).value_counts()
print(my_count)
#in case if you are looking for a count of a particular element
print(my_count['a'])

5. loop and dict

A traditional way to build this functionality is with the use of loops, dictionaries, and conditionals.

First, we build an empty dictionary, and we iterate over the list. Then, we check if the element is available in the dictionary. If it is, then we increase the value by 1. Otherwise, we introduce a new element in the dictionary and assign 1 to it.

Источник

Count Occurrences of Item in Python List

How to count the occurrences of the element or item in a Python list? To count the occurrences of an element in a list in Python, you can use the list.count() method. This method returns the number of times the element appears in the list. And you can also use the Counter class from the collections module to count the occurrences of elements in a list. The Counter class is a dictionary subclass that is specifically designed for counting occurrences of elements.

In this article, I will explain the list.count() , Counter , and other ways to get the count of occurrences of a single value and all values in a list.

1. Quick Examples to Count Occurrence of Item in List

Following are quick examples of how to count the occurrence of an element or item in a Python list.

 # Quick Examples # Count occurrences using count() count = list2.count(67) # Count occurrences using Counter from collections import Counter count = Counter(list2)[67] # Using operator import operator count = operator.countOf(list2,'AA') # Using list comprehension count = len([i for i in list2 if i==12]) # Get count occurrence of all values from collections import Counter count = Counter(list2) # Get all occurrences using pandas pd.Series(list2).value_counts() 

2. Count of Item Occurrence in List using count()

The count() is an inbuilt function available in Python list that is used to get the count of occurrence of an item/element. This function takes a single item as an argument and returns the total occurrence of an item present in the list. If the item is not found, 0 is returned.

2.1 count() Syntax

Following is the syntax of the count()

2.2 Occurance Count Example

Let’s create a list with several integer values, some with duplicates, and use the count() function to find the count of a specific value.

 # Create list of elements list2=[12,54,67,86,89,12,54,67,67,67,66] print("Elements: ",list2) # Count occurrences using count() print("67 occurrence: ",list2.count(67)) print("67 occurrence: ",list2.count(86)) print("67 occurrence: ",list2.count(99)) # Output: # Elements: [12, 54, 67, 86, 89, 12, 54, 67, 67, 67, 66] # 67 occurrence: 4 # 86 occurrence: 1 # 99 occurrence: 0 

Similarly, you can also find the number of occurrences on the list with string values.

3. Count of Item Occurrence in List using Counter()

You can also get the count of occurrences of elements from the list by using the Counter() method from the Python collections module, In order to use the Counter first, we need to import the Counter from the collections module. The Counter class is a dictionary subclass that is specifically designed for counting occurrences of elements.

3.1 Counter() Syntax

Following is the syntax of the counter usage.

 # Syntax of Counter from collections import Counter Counter(list2)[element] 

3.2 Counter Example

The Counter() takes the list as an argument and returns the occurrence count of every element in the list as a Counter class. To get a count for a specific element you need to specify the value using [] . Here’s an example:

 # Import Counter from collections from collections import Counter # Count occurrences using Counter print("67 occurrence: ",Counter(list2)[67]) print("86 occurrence: ",Counter(list2)[86]) print("99 occurrence: ",Counter(list2)[99]) # Output: # 67 occurrence: 4 # 86 occurrence: 1 # 99 occurrence: 0 

4. Using countOf()

The countOf() is similar to the count() function which is available in the operator module. You need to import the operator module to use this.

4.1 countOf() Syntax

Following is the syntax of the countOf().

 # Syntax of countOf() import operator operator.countOf(list2,element) 

4.2 countOf() Example

Here, let’s create a list with strings and use the countOf() to get the count of occurrence of the item.

 # Import operator import operator # Create List with string list2=['AA','AB','AA','BB','AA','CC'] # Get Occurrences of item print("AA occurrence: ",operator.countOf(list2,'AA')) print("CC occurrence: ",operator.countOf(list2,'CC')) print("DD occurrence: ",operator.countOf(list2,'DD')) # Output # AA occurrence: 3 # CC occurrence: 1 # DD occurrence: 0 

5. Using List Comprehension

Like the above scenario, we will use for loop inside the List comprehension to iterate all elements and use if condition to check the condition. So by using the len() function, we will get the total occurrence of element.

5.1 List Comprehension Syntax

 # Here, element is the item, in which all occurrences is counted in list2. # iterator is used to iterate the elements in our input list. len([iterator for iterator in list2 if iterator == element]) 

5.2 Example

Let’s get the total occurrences of element 12.

 # Consider list of elements list2=[12,54,67,86,89,12,54,67,67,67,67] print("Elements: ",list2) # Using List Comprehension print("12 occurrence: ",len([i for i in list2 if i==12])) # Output: # Elements: [12, 54, 67, 86, 89, 12, 54, 67, 67, 67, 67] # 12 occurrence: 2 

6. Using for loop

In this scenario, we will iterate each element using for loop and compare if the iterator is equal to an element or not inside the if condition. If the iterator is equal to our item/element, we will increment the counter(inc) to 1. The result the stored inside the inc variable.

Let’s get the total occurrences of element 67 using for loop.

 # Consider list of elements list2=[12,54,67,86,89,12,54,67,67,67,67] print("Elements: ",list2) # Using for loop to count # occurrence if 67 inc=0 for i in list2: if (i == 67): inc = inc + 1 print("67 occurrence: ",inc) # Output: # Elements: [12, 54, 67, 86, 89, 12, 54, 67, 67, 67, 67] # 67 occurrence: 5 

7. Using value_counts()

Till now, we discussed how to count the total occurrences of a particular item in the list. Now, we will see how to return the total occurrences of all elements from the list using value_counts() method from the pandas module.

Python pandas is a module that is used for Data analysis and visualization. Series is one of the Data structures supported by pandas. It is a one-dimensional data structure. We can apply the value_counts() method on this Series Data structure. To do so, first, you need to convert the list to a series.

7.1 value_counts() Syntax

Following is the syntax of the value_counts()

 # Syntax import pandas as p p.Series(list2).value_counts() 

7.2 Example

Let’s get the count of all element occurrences.

 # Import pandas import pandas as pd # Consider list of elements list2=["hello","hello","java"] print("Elements: ",list2) # Using value_counts() to return all element occurrences pd.Series(list2).value_counts() # Output: # Elements: ['hello', 'hello', 'java'] # hello 2 # java 1 # dtype: int64 

8. Conclusion

In this article, we have seen 6 different ways to count the total occurrences of a particular item in the python list. If you want to know all the element occurrences, then use the value_counts() method available in pandas Series.

You may also like reading:

Источник

Оцените статью