Count same items in list python

The count() method returns the number of times the specified element appears in the list.

Example

# create a list numbers = [2, 3, 5, 2, 11, 2, 7]

# check the count of 2 count = numbers.count(2)

print('Count of 2:', count) # Output: Count of 2: 3

The syntax of the count() method is:

list.count(element)

count() Parameters

The count() method takes a single argument:

  • element - the element to be counted

Return value from count()

The count() method returns the number of times element appears in the list.

Example 1: Use of count()

# vowels list vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# count element 'i' count = vowels.count('i')

# print count print('The count of i is:', count)

# count element 'p' count = vowels.count('p')

# print count print('The count of p is:', count)

Output

The count of i is: 2 The count of p is: 0

Example 2: Count Tuple and List Elements Inside List

# random list random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]

# count element ('a', 'b') count = random.count(('a', 'b'))

# print count print("The count of ('a', 'b') is:", count)

# count element [3, 4] count = random.count([3, 4])

# print count print("The count of [3, 4] is:", count)

Output

The count of ('a', 'b') is: 2 The count of [3, 4] is: 1

An element is said to be duplicate if it occurs multiple times in the list. If you want to find duplicate elements of a python list, you can check the existences of each element in the list, then add it to the duplicates; if the total number of existences of this element is multiple times, then the element is duplicate in the list. This guide will elaborate on example programs that help us count duplicate items of a list.

You can also utilize the Python built-in function, i.e., count (). This function results from the total number of a given item in a list. The count () function counts the string as well as elements present on a list. The nifty thing about a list is that you can add duplicate values to a list. It not only allows duplicate integer values but also you can add duplicate elements of any type like string, float, etc. Let’s elaborate on it with the help of examples. We use the Spyder compiler to explain how python counts duplicate elements in the list.

Example 1

In our first illustration, we use a simple method to find duplicate elements in the python list. Now let’s check how the program works. To run your code, the first thing you have to do is to launch Spyder IDE. So, from the Windows PC search bar, type ‘Spyder’ and then click open. Create a new file by moving to the File menu or simply use a keyboard shortcut ‘Ctrl+Shift+N.’ After creating a new file, write a python code to elaborate how python counts duplicates in the list.

This method uses two loops to pass through the list of elements and check if the first item and second item of each element match any other tuple. Our first step converts ‘ListOfitem’ into a string. Then we initialize the list to append identical values in the list. To check the duplication of the element, we use the if-else statements. If the elements are duplicated, then it prints the element; otherwise moves to the else statement. At last, we use two functions, i.e., print and count. Count function counts the duplicate elements, and the print function displays the resultant output on the console screen.

Count same items in list python

After writing your python code, move to the File menu and save your code file with the ‘.py’ extension below. In our illustration, the file name is ‘CountDuplicate.py’. You can specify any name to your file.

Count same items in list python

Now run your code file or simply use the “F9” key to check the output of a python count duplicate in your console screen. The output is the expected one.

Count same items in list python

Example 2

In our second example, we use the sort and count function to find a duplicate element in the python list. Let’s check how the python code works. Let’s head over to the Spyder compiler in Windows 10 and select a new blank file or use the same file. We used the same python code file in our next illustration, “CountDuplicate.py,” and made changes. This is another way to demonstrate how python counts duplicates in the list.

At first, we initialize a list and use the sort function that sorts original values. Then we use a for loop with nested if statements that traverse the list and count the duplicate elements. If the count function counts any duplicate elements, it is stored in the ‘duplicates’ as we initialize above. If it can’t find any duplicate elements, it calls the ‘append’ function. At last, we use a print function that prints the resultant duplicate values stored in ‘duplicates.’

Count same items in list python

Again, save the python code file for further implementation. Then run the code to check the output of a duplicate python count. After implementing the above program, you will acquire the resultant output. The output can be verified in the attached image.

Count same items in list python

Conclusion

This tutorial discussed how python counts duplicates in the list using the Spyder compiler in Windows 10. We discussed the two simplest methods for its implementation. To get a better understanding, it is recommended to implement them on your operating system. I hope you guys find it helpful.

Count same items in list python

oladejo abdullahi

Posted on Dec 12, 2020

To count the Repeated element in list is very similar to the way we count the character in a string. here are three methods that can be use to do this.

Method 1 : Naive method

just like we learn in counting character in string we need to loop through the entire List for that particular element and then increase the counter when we meet the element again.

Example

you were given a variable MyList containing some elements you were to count the number of 'a' in the string. Here is the codes:

MyList = ["b", "a", "a", "c", "b", "a", "c",'a'] count=0 for i in MyList: if i == 'a': count = count + 1 print ("the number of a in MyList is :", count)

Output:

the number of a in MyList is : 4

Method 2 : Using count()

Using count() is the convinient method in Python to get the occurrence of any element in List. the formula to count element in list with this method is:
list.count('element')

Example1

Let say we need to count 'b' in MyList here is the code:

MyList = ["b", "a", "a", "c", "b", "a", "c",'a'] counter_b=MyList.count('b') print(counter_b)

Output:

Example2

what if we wish to count each of the elements in the List. our code will be..

MyList = ["b", "a", "a", "c", "b", "a", "c",'a'] duplicate_dict={} # a dictionary to store each of them. for i in MyList:#loop through them. duplicate_dict[i]=MyList.count(i) print(duplicate_dict)#to get the occurence of each of the element

Output:

A shortcuts code for the above are:

MyList = ["b", "a", "a", "c", "b", "a", "c",'a'] duplicate_dict = {i:MyList.count(i) for i in MyList} print(duplicate_dict)

Output:

Method3 : Using collections.Counter()

This method works also the same way only that you need to import Counter from the collection before use. Let's see how to use it to solve the same question

#we need to import counter function. from collections import Counter MyList = ["a", "b", "a", "c", "c", "a", "c"] duplicate_dict = Counter(MyList) print(duplicate_dict)#to get occurence of each of the element. print(duplicate_dict['a'])# to get occurence of specific element.

Output:

Counter({'a': 3, 'c': 3, 'b': 1}) 3

remember to import the Counter if you are using Method otherwise you get error. I hope you find this helpful, yeah keep on enjoying coding.