Im trying to find the number of whole words in a list of strings, heres the list
mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"]
expected outcome:
4
1
2
3
There are 4 words in mylist[0], 1 in mylist[1] and so on
for x, word in enumerate(mylist):
for i, subwords in enumerate(word):
print i
Totally doesnt work….
What do you guys think?
asked Sep 16, 2013 at 11:45
Boosted_d16Boosted_d16
13k34 gold badges95 silver badges156 bronze badges
1
Use str.split
:
>>> mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"]
>>> for item in mylist:
... print len(item.split())
...
4
1
2
3
answered Sep 16, 2013 at 11:50
Ashwini ChaudharyAshwini Chaudhary
242k58 gold badges456 silver badges502 bronze badges
The simplest way should be
num_words = [len(sentence.split()) for sentence in mylist]
answered Sep 16, 2013 at 11:50
Hari MenonHari Menon
33.1k14 gold badges82 silver badges108 bronze badges
You can use NLTK:
import nltk
mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"]
print(map(len, map(nltk.word_tokenize, mylist)))
Output:
[4, 1, 2, 3]
answered Aug 11, 2015 at 23:58
for x,word in enumerate(mylist):
print len(word.split())
answered Sep 16, 2013 at 12:12
a="hello world aa aa aa abcd hello double int float float hello"
words=a.split(" ")
words
dic={}
for word in words:
if dic.has_key(word):
dic[word]=dic[word]+1
else:
dic[word]=1
dic
iScrE4m
8821 gold badge11 silver badges29 bronze badges
answered Sep 13, 2016 at 10:30
2
We can count the number of a word’s ocurrence in a list using the Counter
function.
from collection import Counter
string = ["mahesh","hello","nepal","nikesh","mahesh","nikesh"]
count_each_word = Counter(string)
print(count_each_word)
Output:
Counter({mahesh:2},{hello:1},{nepal:1},{nikesh:2})
answered May 16, 2019 at 1:31
1
This is another solution:
You can clean your data first and then count the result, something like that:
mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"]
for item in mylist:
for char in "-.,":
item = item.replace(char, '')
item_word_list = item.split()
print(len(item_word_list))
The result:
4
1
2
3
answered Aug 26, 2019 at 16:38
neosergioneosergio
4325 silver badges14 bronze badges
mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"]
flage = True
for string1 in mylist:
n = 0
for s in range(len(string1)):
if string1[s] == ' ' and flage == False:
n+=1
if string1[s] == ' ':
flage = True
else:
flage = False
print(n+1)
answered Mar 11, 2020 at 19:55
lista="Write a Python function to count the number of occurrences of a given characte Write a of occurrences of a given characte"
dic=lista.split(" ")
wcount={}
for i in dic:
if i in wcount:
wcount[i]+=1
else:
wcount[i]=1
print(wcount)
picture with solution
answered Mar 30 at 10:45
Introduction
Counting the word frequency in a list element in Python is a relatively common task — especially when creating distribution data for histograms.
Say we have a list ['b', 'b', 'a']
— we have two occurrences of «b» and one of «a». This guide will show you three different ways to count the number of word occurrences in a Python list:
- Using Pandas and NumPy
- Using the
count()
Function - Using the Collection Module’s
Counter
- Using a Loop and a Counter Variable
In practice, you’ll use Pandas/Numpy, the count()
function or a Counter
as they’re pretty convenient to use.
Using Pandas and NumPy
The shortest and easiest way to get value counts in an easily-manipulable format (DataFrame
) is via NumPy and Pandas. We can wrap the list into a NumPy array, and then call the value_counts()
method of the pd
instance (which is also available for all DataFrame
instances):
import numpy as np
import pandas as pd
words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']
pd.value_counts(np.array(words))
This results in a DataFrame
that contains:
hello 3
goodbye 1
bye 1
howdy 1
hi 1
dtype: int64
You can access its values
field to get the counts themselves, or index
to get the words themselves:
df = pd.value_counts(np.array(words))
print('Index:', df.index)
print('Values:', df.values)
This results in:
Index: Index(['hello', 'goodbye', 'bye', 'howdy', 'hi'], dtype='object')
Values: [3 1 1 1 1]
Using the count() Function
The «standard» way (no external libraries) to get the count of word occurrences in a list is by using the list object’s count()
function.
The count()
method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.
The complexity of the
count()
function is O(n), wheren
is the number of factors present in the list.
The code below uses count()
to get the number of occurrences for a word in a list:
words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']
print(f'"hello" appears {words.count("hello")} time(s)')
print(f'"howdy" appears {words.count("howdy")} time(s)')
This should give us the same output as before using loops:
"hello" appears 3 time(s)
"howdy" appears 1 time(s)
The count()
method offers us an easy way to get the number of word occurrences in a list for each individual word.
Using the Collection Module’s Counter
The Counter
class instance can be used to, well, count instances of other objects. By passing a list into its constructor, we instantiate a Counter
which returns a dictionary of all the elements and their occurrences in a list.
From there, to get a single word’s occurrence you can just use the word as a key for the dictionary:
from collections import Counter
words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']
word_counts = Counter(words)
print(f'"hello" appears {word_counts["hello"]} time(s)')
print(f'"howdy" appears {word_counts["howdy"]} time(s)')
This results in:
"hello" appears 3 time(s)
"howdy" appears 1 time(s)
Using a Loop and a Counter Variable
Ultimately, a brute force approach that loops through every word in the list, incrementing a counter by one when the word is found, and returning the total word count will work!
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Of course, this method gets more inefficient as the list size grows, it’s just conceptually easy to understand and implement.
The code below uses this approach in the count_occurrence()
method:
def count_occurrence(words, word_to_count):
count = 0
for word in words:
if word == word_to_count:
# update counter variable
count = count + 1
return count
words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']
print(f'"hello" appears {count_occurrence(words, "hello")} time(s)')
print(f'"howdy" appears {count_occurrence(words, "howdy")} time(s)')
If you run this code you should see this output:
"hello" appears 3 time(s)
"howdy" appears 1 time(s)
Nice and easy!
Most Efficient Solution?
Naturally — you’ll be searching for the most efficient solution if you’re dealing with a large corpora of words. Let’s benchmark all of these to see how they perform.
The task can be broken down into finding occurrences for all words or a single word, and we’ll be doing benchmarks for both, starting with all words:
import numpy as np
import pandas as pd
import collections
def pdNumpy(words):
def _pdNumpy():
return pd.value_counts(np.array(words))
return _pdNumpy
def countFunction(words):
def _countFunction():
counts = []
for word in words:
counts.append(words.count(word))
return counts
return _countFunction
def counterObject(words):
def _counterObject():
return collections.Counter(words)
return _counterObject
import timeit
words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']
print("Time to execute:n")
print("Pandas/Numpy: %ss" % timeit.Timer(pdNumpy(words)).timeit(1000))
print("count(): %ss" % timeit.Timer(countFunction(words)).timeit(1000))
print("Counter: %ss" % timeit.Timer(counterObject(words)).timeit(1000))
Which results in:
Time to execute:
Pandas/Numpy: 0.33886080000047514s
count(): 0.0009540999999444466s
Counter: 0.0019409999995332328s
The count()
method is extremely fast compared to the other variants, however, it doesn’t give us the labels associated with the counts like the other two do.
If you need the labels — the Counter
outperforms the inefficient process of wrapping the list in a NumPy array and then counting.
On the other hand, you can make use of DataFrame’s methods for sorting or other manipulation that you can’t do otherwise. Counter
has some unique methods as well.
Ultimately, you can use the Counter
to create a dictionary and turn the dictionary into a DataFrame
as as well, to leverage the speed of Counter
and the versatility of DataFrame
s:
df = pd.DataFrame.from_dict([Counter(words)]).T
If you don’t need the labels — count()
is the way to go.
Alternatively, if you’re looking for a single word:
import numpy as np
import pandas as pd
import collections
def countFunction(words, word_to_search):
def _countFunction():
return words.count(word_to_search)
return _countFunction
def counterObject(words, word_to_search):
def _counterObject():
return collections.Counter(words)[word_to_search]
return _counterObject
def bruteForce(words, word_to_search):
def _bruteForce():
counts = []
count = 0
for word in words:
if word == word_to_search:
# update counter variable
count = count + 1
counts.append(count)
return counts
return _bruteForce
import timeit
words = ['hello', 'goodbye', 'howdy', 'hello', 'hello', 'hi', 'bye']
print("Time to execute:n")
print("count(): %ss" % timeit.Timer(countFunction(words, 'hello')).timeit(1000))
print("Counter: %ss" % timeit.Timer(counterObject(words, 'hello')).timeit(1000))
print("Brute Force: %ss" % timeit.Timer(bruteForce(words, 'hello')).timeit(1000))
Which results in:
Time to execute:
count(): 0.0001573999998072395s
Counter: 0.0019498999999996158s
Brute Force: 0.0005682000000888365s
The brute force search and count()
methods outperform the Counter
, mainly because the Counter
inherently counts all words instead of one.
Conclusion
In this guide, we explored finding the occurrence of the word in a Python list, assessing the efficiency of each solution and weighing when each is more suitable.
In this tutorial, you’ll learn how to use Python to count the number of words and word frequencies in both a string and a text file. Being able to count words and word frequencies is a useful skill. For example, knowing how to do this can be important in text classification machine learning algorithms.
By the end of this tutorial, you’ll have learned:
- How to count the number of words in a string
- How to count the number of words in a text file
- How to calculate word frequencies using Python
Reading a Text File in Python
The processes to count words and calculate word frequencies shown below are the same for whether you’re considering a string or an entire text file. Because of this, this section will briefly describe how to read a text file in Python.
If you want a more in-depth guide on how to read a text file in Python, check out this tutorial here. Here is a quick piece of code that you can use to load the contents of a text file into a Python string:
# Reading a Text File in Python
file_path = '/Users/datagy/Desktop/sample_text.txt'
with open(file_path) as file:
text = file.read()
I encourage you to check out the tutorial to learn why and how this approach works. However, if you’re in a hurry, just know that the process opens the file, reads its contents, and then closes the file again.
Count Number of Words In Python Using split()
One of the simplest ways to count the number of words in a Python string is by using the split()
function. The split function looks like this:
# Understanding the split() function
str.split(
sep=None # The delimiter to split on
maxsplit=-1 # The number of times to split
)
By default, Python will consider runs of consecutive whitespace to be a single separator. This means that if our string had multiple spaces, they’d only be considered a single delimiter. Let’s see what this method returns:
# Splitting a string with .split()
text = 'Welcome to datagy! Here you will learn Python and data science.'
print(text.split())
# Returns: ['Welcome', 'to', 'datagy!', 'Here', 'you', 'will', 'learn', 'Python', 'and', 'data', 'science.']
We can see that the method now returns a list of items. Because we can use the len()
function to count the number of items in a list, we’re able to generate a word count. Let’s see what this looks like:
# Counting words with .split()
text = 'Welcome to datagy! Here you will learn Python and data science.'
print(len(text.split()))
# Returns: 11
Count Number of Words In Python Using Regex
Another simple way to count the number of words in a Python string is to use the regular expressions library, re
. The library comes with a function, findall()
, which lets you search for different patterns of strings.
Because we can use regular expression to search for patterns, we must first define our pattern. In this case, we want patterns of alphanumeric characters that are separated by whitespace.
For this, we can use the pattern w+
, where w
represents any alphanumeric character and the +
denotes one or more occurrences. Once the pattern encounters whitespace, such as a space, it will stop the pattern there.
Let’s see how we can use this method to generate a word count using the regular expressions library, re
:
# Counting words with regular expressions
import re
text = 'Welcome to datagy! Here you will learn Python and data science.'
print(len(re.findall(r'w+', text)))
# Returns: 11
Calculating Word Frequencies in Python
In order to calculate word frequencies, we can use either the defaultdict class or the Counter class. Word frequencies represent how often a given word appears in a piece of text.
Using defaultdict To Calculate Word Frequencies in Python
Let’s see how we can use defaultdict to calculate word frequencies in Python. The defaultdict extend on the regular Python dictionary by providing helpful functions to initialize missing keys.
Because of this, we can loop over a piece of text and count the occurrences of each word. Let’s see how we can use it to create word frequencies for a given string:
# Creating word frequencies with defaultdict
from collections import defaultdict
import re
text = 'welcome to datagy! datagy will teach data. data is fun. data data data!'
counts = defaultdict(int)
for word in re.findall('w+', text):
counts[word] += 1
print(counts)
# Returns:
# defaultdict(<class 'int'>, {'welcome': 1, 'to': 1, 'datagy': 2, 'will': 1, 'teach': 1, 'data': 5, 'is': 1, 'fun': 1})
Let’s break down what we did here:
- We imported both the
defaultdict
function and there
library - We loaded some text and instantiated a defaultdict using the
int
factory function - We then looped over each word in the word list and added one for each time it occurred
Using Counter to Create Word Frequencies in Python
Another way to do this is to use the Counter
class. The benefit of this approach is that we can even easily identify the most frequent word. Let’s see how we can use this approach:
# Creating word frequencies with Counter
from collections import Counter
import re
text = 'welcome to datagy! datagy will teach data. data is fun. data data data!'
counts = Counter(re.findall('w+', text))
print(counts)
# Returns:
# Counter({'data': 5, 'datagy': 2, 'welcome': 1, 'to': 1, 'will': 1, 'teach': 1, 'is': 1, 'fun': 1})
Let’s break down what we did here:
- We imported our required libraries and classes
- We passed the resulting list from the
findall()
function into theCounter
class - We printed the result of this class
One of the perks of this is that we can easily find the most common word by using the .most_common()
function. The function returns a sorted list of tuples, ordering the items from most common to least common. Because of this, we can simply access the 0th index to find the most common word:
# Finding the Most Common Word
from collections import Counter
import re
text = 'welcome to datagy! datagy will teach data. data is fun. data data data!'
counts = Counter(re.findall('w+', text))
print(counts.most_common()[0])
# Returns:
# ('data', 5)
Conclusion
In this tutorial, you learned how to generate word counts and word frequencies using Python. You learned a number of different ways to count words including using the .split()
method and the re
library. Then, you learned different ways to generate word frequencies using defaultdict
and Counter
. Using the Counter method, you were able to find the most frequent word in a string.
Additional Resources
To learn more about related topics, check out the tutorials below:
- Python
str.split()
– Official Documentation - Python Defaultdict: Overview and Examples
- Python: Count Number of Occurrences in List (6 Ways)
- Python: Count Number of Occurrences in a String (4 Ways!)
Python Count The Frequency Of Words In A List With Code Examples
Table of Contents Show
- How do you count the frequency of a string in a list Python?
- How do you count occurrences in a list in Python?
- How do you count frequency in words?
- How do you count occurrences of each word in a string in Python?
- How do you count occurrences in a list?
- How do you count repeated letters in Python?
- How do you count repeated elements in a string Python?
- How do you print the frequency of words in python?
- How do you count occurrences of each word in a string?
- How do you count the frequency of text values in a column?
- Visualize Python code execution:
- How to Count the Number of Occurrences in the List?
- 1) Using count() method
- 2) Using a loop
- 3) Using countof() method
- 4) Using counter() method
- 5) Using pandas library
- 6) Using loops and dict in python
We will use programming in this lesson to attempt to solve the Python Count The Frequency Of Words In A List puzzle. This is demonstrated by the following code.
from collections import Counter
list1=[‘apple’,’egg’,’apple’,’banana’,’egg’,’apple’]
counts = Counter(list1)
print(counts)
# Counter({‘apple’: 3, ‘egg’: 2, ‘banana’: 1})
As we have seen, the Python Count The Frequency Of Words In A List problem was solved by using a number of different instances.
How do you count the frequency of a string in a list Python?
We can use the counter() method from the collections module to count the frequency of elements in a list.20-Aug-2021
How do you count occurrences in a list in Python?
The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.12-Nov-2021
How do you count frequency in words?
Approach: To solve the problem mentioned above we have to follow the steps given below:
- Use a Map data structure to store the occurrence of each word in the string.
- Traverse the entire string and check whether the current word is present in map or not.
- Traverse in the map and print the frequency of each word.
How do you count occurrences of each word in a string in Python?
Python Code: def word_count(str): counts = dict() words = str. split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count(‘the quick brown fox jumps over the lazy dog. ‘))19-Aug-2022
How do you count occurrences in a list?
Using the count() Function The «standard» way (no external libraries) to get the count of word occurrences in a list is by using the list object’s count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.28-Dec-2021
How do you count repeated letters in Python?
Python
- string = «Great responsibility»;
- print(«Duplicate characters in a given string: «);
- #Counts each character present in the string.
- for i in range(0, len(string)):
- count = 1;
- for j in range(i+1, len(string)):
- if(string[i] == string[j] and string[i] != ‘ ‘):
- count = count + 1;
How do you count repeated elements in a string Python?
Step 1: Declare a String and store it in a variable. Step 2: Use 2 loops to find the duplicate characters. Outer loop will be used to select a character and initialize variable count to 1. Step 3: Inner loop will be used to compare the selected character with remaining characters of the string.
How do you print the frequency of words in python?
Using FreqDist() The natural language tool kit provides the FreqDist function which shows the number of words in the string as well as the number of distinct words. Applying the most_common() gives us the frequency of each word.20-Dec-2019
How do you count occurrences of each word in a string?
Approach: First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.27-Jul-2022
How do you count the frequency of text values in a column?
You can use the COUNTIF(range, criteria) function to count how often specific text occurs in an Excel column.02-Sept-2021
Write a Python program to count the occurrences of each word in a given sentence.
Sample Solution:-
Python Code:
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print( word_count(‘the quick brown fox jumps over the lazy dog.’))
Sample Output:
{‘the’: 2, ‘jumps’: 1, ‘brown’: 1, ‘lazy’: 1, ‘fox’: 1, ‘over’: 1, ‘quick’: 1, ‘dog.’: 1}
Flowchart:
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to remove the characters which have odd index values of a given string.
Next: Write a Python script that takes input from the user and displays that input back in upper and lower cases.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource’s quiz.
Anti-gravity:
import antigravity
antigravity.fly()
- Exercises: Weekly Top 16 Most Popular Topics
- SQL Exercises, Practice, Solution — JOINS
- SQL Exercises, Practice, Solution — SUBQUERIES
- JavaScript basic — Exercises, Practice, Solution
- Java Array: Exercises, Practice, Solution
- C Programming Exercises, Practice, Solution : Conditional Statement
- HR Database — SORT FILTER: Exercises, Practice, Solution
- C Programming Exercises, Practice, Solution : String
- Python Data Types: Dictionary — Exercises, Practice, Solution
- Python Programming Puzzles — Exercises, Practice, Solution
- C++ Array: Exercises, Practice, Solution
- JavaScript conditional statements and loops — Exercises, Practice, Solution
- C# Sharp Basic Algorithm: Exercises, Practice, Solution
- Python Lambda — Exercises, Practice, Solution
- Python Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation
Python is well known for its easy syntax, fast implementation, and, most importantly, large support of multiple data structures. Lists are one of those data structures in python which helps to store large amounts of sequential data in a single variable. As huge data is stored under the same variable, it is sometimes quite difficult to manually identify whether the given element is present in the lists, and if yes, how many times. Therefore, in this article, we will study the various ways to count the number of occurrences in the list in python. To recall the concepts of python lists in detail, visit our article “3 Ways to Convert List to Tuple”.
How to Count the Number of Occurrences in the List?
There are six ways by which you can count the number of occurrences of the element in the list. Let us study them all in brief below:
1) Using count() method
count() is the in-built function by which python count occurrences in list. It is the easiest among all other methods used to count the occurrence. Count() methods take one argument, i.e., the element for which the number of occurrences is to be counted.
For example:
sample_list = [«a», «ab», «a», «abc», «ab», «ab»] print(sample_list.count(«a»)) print(sample_list.count(«ab»))
Output
2) Using a loop
Another simple approach to counting the occurrence is by using a loop with the counter variable. Here, the counter variable keeps increasing its value by one each time after traversing through the given element. At last, the value of the counter variable displays the number of occurrences of the element.
For example:
def countElement(sample_list, element): return sample_list.count(element) sample_list = [«a», «ab», «a», «abc», «ab», «ab»] element = «ab» print(‘{} has occurred {} times‘.format(element, countElement(sample_list, element)))
Output
3) Using countof() method
Operator module from python library consists of countof() method which helps to return the number of occurrence of the element from the lists. This method takes two arguments, i.e., the list in which the count needs to be performed and the element which needs to be found. Moreover, you have to import the operator module before beginning the program using the “import” keyword as shown below:
For example:
sample_list = [«a», «ab», «a», «abc», «ab», «ab»] import operator as op print(op.countOf(sample_list,«a»))
Output
4) Using counter() method
Python possesses an in-built module named collections, including multiple methods to ease your programming. One such method is a counter() method where elements are stored as a dictionary with keys and counts as values.
Therefore, the counter() method helps you return the total number of occurrences of a given element inside the given list by taking one parameter as the list in which the element is to be counted. Remember that you have to import the collections module to use the counter() method as shown in the below example:
For example:
sample_list = [«a», «ab», «a», «abc», «ab», «ab»] from collections import Counter print(Counter(sample_list)) c = Counter(sample_list) print(c[«a»])
Output
Counter({‘ab’: 3, ‘a’: 2, ‘abc’: 1}) 2
5) Using pandas library
Pandas is the in-built python library, highly popular for data analysis and data manipulation. It is an open-source tool with a large range of features and is widely used in the domains like machine learning and artificial intelligence. To learn more about pandas, please visit our article “Numpy vs Pandas.”
Pandas possess a wide range of default methods, one of which is the value_count() method. Along with the value_count() method, pandas use series, i.e., a one-dimensional array with axis label.
To count the occurrence of elements using pandas, you have to convert the given list into the series and then use the value_count() method, which returns the object in descending order. By these, you can easily note that the first element is always the most frequently occurring element.
Check out the below example for a better understanding of the Pandas library
For example:
import pandas as pd sample_list = [«a», «ab», «a», «abc», «ab», «ab»] count = pd.Series(sample_list).value_counts() print(count[«a»])
Output
6) Using loops and dict in python
This is the most traditional method by which python count occurrences in the list that is by using the loop, conditional statement, and dictionaries. By this method, you have to create the empty dictionary and then iterate over the list. Later, check if the element present in the list is available in the dictionary or not. If yes, then increase its value by one; otherwise, introduce a new element in the dictionary and assign 1 to it. Repeat the same process until all the elements in the lists are visited.
Remember that this method is quite different from the previous method using the loop and the counter variable. The early mentioned method does not make use of dictionary data structure, whereas this one does. At last, print the count of occurrence of each element as shown in the below example:
For example:
sample_list = [«a», «ab», «a», «abc», «ab», «ab»] def countOccurrence(a): k = {} for j in a: if j in k: k[j] +=1 else: k[j] =1 return k
print(countOccurrence(sample_list))
Output
{‘a’: 2, ‘ab’: 3, ‘abc’: 1}
Conclusion
Programming is all about reducing manual tasks and shifting to automation. Counting the occurrence of elements from the large dataset manually is quite a tedious and time-consuming task. Therefore, python provides various methods by which you can count the occurrence of elements easily and quickly with few lines of code, just like shown in the article above. It is recommended to learn and understand all these methods to make your programming effective and efficient.