{"id":123763,"date":"2022-04-10T17:41:48","date_gmt":"2022-04-10T17:41:48","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=293994"},"modified":"2022-04-10T17:41:48","modified_gmt":"2022-04-10T17:41:48","slug":"how-to-count-the-occurrences-of-a-list-element","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/04\/10\/how-to-count-the-occurrences-of-a-list-element\/","title":{"rendered":"How to Count the Occurrences\u00a0of a List Element"},"content":{"rendered":"<p>In this article, you&#8217;ll learn how to count the occurrences of a selected <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\">List<\/a> element in Python. <\/p>\n<p>To make it more fun, we have the following running scenario:<\/p>\n<p><em>A Teacher from <strong>Orchard Elementary<\/strong> would like a script created for the 4th-grade students called &#8220;<strong>Count-Me<\/strong>&#8220;. <\/em>She would like this script to do the following:<\/p>\n<ul>\n<li><em>First, generate and display 10 random numbers on a single line.<\/em><\/li>\n<li><em>Next, generate and display one (1) random number to find.<\/em><\/li>\n<li><em>Prompt for the total occurrences found.<\/em><\/li>\n<li><em>Display a message validating the solution.<\/em><\/li>\n<\/ul>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.1.0\/72x72\/1f4ac.png\" alt=\"\ud83d\udcac\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Question<\/strong>: How would we write the <a href=\"https:\/\/blog.finxter.com\/python-developer-income-and-opportunity\/\" data-type=\"post\" data-id=\"189354\" target=\"_blank\" rel=\"noreferrer noopener\">Python<\/a> code to accomplish this task?<\/p>\n<p>We can accomplish this task by one of the following options:<\/p>\n<ul>\n<li><strong>Method 1<\/strong>: Use <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/numpy-tutorial\/\" data-type=\"post\" data-id=\"1356\" target=\"_blank\">NumPy<\/a> and <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-list-count\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-list-count\/\" target=\"_blank\"><code>count()<\/code><\/a><\/li>\n<li><strong>Method 2<\/strong>: Use operator <code>countOf()<\/code><\/li>\n<li><strong>Method 3<\/strong>: Use a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-loops\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-loops\/\" target=\"_blank\">For Loop<\/a><\/li>\n<li><strong>Method 4<\/strong>: Use a <code>Counter()<\/code><\/li>\n<\/ul>\n<hr class=\"wp-block-separator\" \/>\n<h2>Preparation<\/h2>\n<p class=\"wp-embed-aspect-16-9 wp-has-aspect-ratio\">Before any data manipulation can occur, one (1) new library will require installation.<\/p>\n<ul>\n<li>The <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/numpy-tutorial\/\" data-type=\"post\" data-id=\"1356\" target=\"_blank\"><em>NumPy<\/em><\/a> library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions. <\/li>\n<\/ul>\n<p>To install this library, navigate to an <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/best-python-ide\/\" data-type=\"post\" data-id=\"8106\" target=\"_blank\">IDE<\/a> terminal. At the command prompt (<code>$<\/code>), execute the code below. For the terminal used in this example, the command prompt is a dollar sign (<code>$<\/code>). Your terminal prompt may be different.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$ pip install numpy<\/pre>\n<p>Hit the <code>&lt;Enter&gt;<\/code> key on the keyboard to start the installation process.<\/p>\n<p>If the installation was successful, a message displays in the terminal indicating the same.<\/p>\n<hr class=\"wp-block-separator\" \/>\n<p>Feel free to view the PyCharm installation guide for the required library.<\/p>\n<ul>\n<li><a href=\"https:\/\/blog.finxter.com\/how-to-install-numpy-on-pycharm\/#:~:text=Click%20the%20Python%20Interpreter%20tab,and%20close%20all%20popup%20windows.\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/how-to-install-numpy-on-pycharm\/#:~:text=Click%20the%20Python%20Interpreter%20tab,and%20close%20all%20popup%20windows.\">How to install NumPy on PyCharm<\/a><\/li>\n<\/ul>\n<hr class=\"wp-block-separator\" \/>\n<p id=\"block-3b5c9c73-276c-4b84-a1bc-d5ba1de38d56\">Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.<\/p>\n<pre class=\"EnlighterJSRAW wp-embed-aspect-16-9 wp-has-aspect-ratio\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import numpy as np\nimport random\nimport operator\nfrom collections import Counter<\/pre>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.1.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/>&nbsp;<strong>Note<\/strong>: The <code>counter <\/code>and <code>collections <\/code>libraries are built-in to Python and do not require installation.<\/p>\n<hr class=\"wp-block-separator\" \/>\n<h2>Method 1: Use NumPy and count()<\/h2>\n<p>To count the total occurrences of an element inside a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\">List<\/a>, this example will use <a href=\"https:\/\/blog.finxter.com\/how-to-install-numpy-on-pycharm\/#:~:text=Click%20the%20Python%20Interpreter%20tab,and%20close%20all%20popup%20windows.\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/how-to-install-numpy-on-pycharm\/#:~:text=Click%20the%20Python%20Interpreter%20tab,and%20close%20all%20popup%20windows.\">NumPy <\/a>and the <code><a href=\"https:\/\/blog.finxter.com\/python-list-count\/\" data-type=\"post\" data-id=\"6984\" target=\"_blank\" rel=\"noreferrer noopener\">count()<\/a><\/code> function.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"1-3\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">the_list = list(np.random.choice(20, 20))\ndup_num = the_list[random.randint(0, 19)]\ndup_count = the_list.count(dup_num) try: print(the_list) check = int(input(f'How man times does the number {dup_num} appear in the list? ')) if check == dup_count: print(f'Correct! The answer is {check}.') else: print(f'Sorry! Try again!')\nexcept ValueError: print(f'Incorrect value. Bye')<\/pre>\n<p>The previous code snippet performs the following steps:<\/p>\n<ul>\n<li>Our first line generates and saves 20 random numbers to <code>the_list<\/code>. <\/li>\n<li>Next, <code>dup_num<\/code> is created by generating and saving one (1) <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-generate-a-sequence-of-numbers\/\" data-type=\"post\" data-id=\"290181\" target=\"_blank\">random number<\/a> from <code>the_list<\/code>. <\/li>\n<li>Finally, we determine how many occurrences of <code>dup_num<\/code> were found using <code>count()<\/code>. <\/li>\n<li>The result saves to <code>dup_count<\/code>.<\/li>\n<\/ul>\n<p>Inside the <code><a href=\"https:\/\/blog.finxter.com\/manually-raising-throwing-an-exception-python\/\" data-type=\"post\" data-id=\"209773\" target=\"_blank\" rel=\"noreferrer noopener\">try<\/a><\/code> statement, <code>the_list <\/code>is output to the terminal. <\/p>\n<p>The user is prompted to enter the total number of occurrences. To confirm, the user presses the <code>&lt;Enter&gt;<\/code> key. The value entered is then compared to <code>dup_count<\/code>, and a message indicates the outcome.<\/p>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.1.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/>&nbsp;<strong>Note<\/strong>: Click here for details on the <a href=\"https:\/\/blog.finxter.com\/how-to-catch-and-print-exception-messages-in-python\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/how-to-catch-and-print-exception-messages-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">try\/except<\/a> statement.<\/p>\n<hr class=\"wp-block-separator\" \/>\n<h2>Method 2: Use operator countOf()<\/h2>\n<p>To count the total occurrences of a specified element inside a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\">List<\/a>, this example will use the <code>countOf()<\/code> function.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"1-3\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">the_list = [random.randrange(0, 20) for num in range(20)]\ndup_num = the_list[random.randint(0, 19)]\ndup_count = operator.countOf(the_list, dup_num) try: print(the_list) check = int(input(f'How man times does the number {dup_num} appear in the list? ')) if check == dup_count: print(f'Correct! The answer is {check}.') else: print(f'Sorry! Try again!')\nexcept ValueError: print(f'Incorrect value. Bye')<\/pre>\n<p>This code snippet performs the following steps:<\/p>\n<ul>\n<li>Our first line generates and saves 20 random numbers to <code>the_list<\/code>. <\/li>\n<li>Next, <code>dup_num<\/code> is created by generating and saving one (1) random number from <code>the_list<\/code>. <\/li>\n<li>Finally, we determine how many occurrences of <code>dup_num<\/code> were found using <code><code>operator.countOf()<\/code><\/code>. <\/li>\n<li>The result saves to <code>dup_count<\/code>.<\/li>\n<\/ul>\n<p>Inside the <code>try<\/code> statement, <code>the_list <\/code>is output to the terminal. <\/p>\n<p>The user is prompted to enter the total number of occurrences. To confirm, the user presses the <code>&lt;Enter&gt;<\/code> key. <\/p>\n<p>The value entered is then compared to <code>dup_count<\/code>, and a message indicates the outcome.<\/p>\n<hr class=\"wp-block-separator\" \/>\n<h2>Method 3: Use a For Loop<\/h2>\n<p>To count the total occurrences of a specified element inside a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\">List<\/a>, this example will use the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-loops\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-loops\/\" target=\"_blank\">For Loop<\/a>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"1-7\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">the_list = [random.randrange(0, 20) for num in range(20)]\ndup_num = the_list[random.randint(0, 19)] dup_count = 0\nfor i in the_list: if i == dup_num: dup_count += 1 try: print(the_list) check = int(input(f'How man times does the number {dup_num} appear in the list? ')) if check == dup_count: print(f'Correct! The answer is {check}.') else: print(f'Sorry! Try again!')\nexcept ValueError: print(f'Incorrect value. Bye')<\/pre>\n<p>The previous code snippet performs the following steps:<\/p>\n<ul>\n<li>Our first line generates and saves 20 random numbers to <code>the_list<\/code>. <\/li>\n<li>Next, <code>dup_num<\/code> is created by generating and saving one (1) random number from <code>the_list<\/code>. <\/li>\n<li>Finally, a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-loops\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-loops\/\" target=\"_blank\">For Loop<\/a> is instantiated. Upon each Loop, the element is matched against <code>dup_num<\/code>. <\/li>\n<li>If found, <code>dup_count<\/code> is increased by one (1).<\/li>\n<\/ul>\n<p>Inside the <code>try<\/code> statement, <code>the_list <\/code>is output to the terminal. <\/p>\n<p>The user is prompted to enter the total number of occurrences. To confirm, the user presses the <code>&lt;Enter&gt;<\/code> key. <\/p>\n<p>The value entered is then compared to <code>dup_count<\/code>, and a message indicates the outcome.<\/p>\n<hr class=\"wp-block-separator\" \/>\n<h2>Method 4: Counter()<\/h2>\n<p>To count the total occurrences of a specified element inside a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\">List<\/a>, this example will use the <code>Counter()<\/code> initializer method.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"1-4\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">the_list = [random.randrange(0, 20) for num in range(20)]\ndup_num = the_list[random.randint(0, 19)]\nd = Counter(the_list)\ndup_count = d[dup_num] try: print(the_list) check = int(input(f'How man times does the number {dup_num} appear in the list? ')) if check == dup_count: print(f'Correct! The answer is {check}.') else: print(f'Sorry! Try again!')\nexcept ValueError: print(f'Incorrect value. Bye')<\/pre>\n<p>The previous code snippet performs the following steps:<\/p>\n<ul>\n<li>Our first line generates and saves 20 random numbers to <code>the_list<\/code>. <\/li>\n<li>Next, <code>dup_num<\/code> is created by generating and saving one (1) random number from <code>the_list<\/code>. <\/li>\n<li>Finally, a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-loops\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-loops\/\" target=\"_blank\">For Loop<\/a> is instantiated. Upon each Loop, an element is matched against <code>dup_num<\/code>. <\/li>\n<li>If found, <code>dup_count<\/code> is increased by one (1).<\/li>\n<\/ul>\n<p>Inside the <code>try<\/code> statement, <code>the_list <\/code>is output to the terminal. <\/p>\n<p>The user is prompted to enter the total number of occurrences. To confirm, the user presses the <code>&lt;Enter&gt;<\/code> key. <\/p>\n<p>The value entered is then compared to <code>dup_count<\/code>, and a message indicates the outcome.<\/p>\n<hr class=\"wp-block-separator\" \/>\n<h2>Summary<\/h2>\n<p>These four (4) methods of counting occurrences of a specified element inside a List should give you enough information to select the best one for your coding requirements.<\/p>\n<p>Good Luck &amp; Happy Coding!<\/p>\n<hr class=\"wp-block-separator\" \/>\n","protected":false},"excerpt":{"rendered":"<p>In this article, you&#8217;ll learn how to count the occurrences of a selected List element in Python. To make it more fun, we have the following running scenario: A Teacher from Orchard Elementary would like a script created for the 4th-grade students called &#8220;Count-Me&#8220;. She would like this script to do the following: First, generate [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-123763","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123763","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=123763"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123763\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=123763"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=123763"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=123763"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}