[Tut] How to Count the Occurrences of a List Element - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Count the Occurrences of a List Element (/thread-99225.html) |
[Tut] How to Count the Occurrences of a List Element - xSicKxBot - 04-16-2022 How to Count the Occurrences of a List Element <div><p>In this article, you’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> <p>To make it more fun, we have the following running scenario:</p> <p><em>A Teacher from <strong>Orchard Elementary</strong> would like a script created for the 4th-grade students called “<strong>Count-Me</strong>“. </em>She would like this script to do the following:</p> <ul> <li><em>First, generate and display 10 random numbers on a single line.</em></li> <li><em>Next, generate and display one (1) random number to find.</em></li> <li><em>Prompt for the total occurrences found.</em></li> <li><em>Display a message validating the solution.</em></li> </ul> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4ac.png" alt="?" 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> <p>We can accomplish this task by one of the following options:</p> <ul> <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> <li><strong>Method 2</strong>: Use operator <code>countOf()</code></li> <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> <li><strong>Method 4</strong>: Use a <code>Counter()</code></li> </ul> <hr class="wp-block-separator" /> <h2>Preparation</h2> <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> <ul> <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> </ul> <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> <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> <p>Hit the <code><Enter></code> key on the keyboard to start the installation process.</p> <p>If the installation was successful, a message displays in the terminal indicating the same.</p> <hr class="wp-block-separator" /> <p>Feel free to view the PyCharm installation guide for the required library.</p> <ul> <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> </ul> <hr class="wp-block-separator" /> <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> <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 import random import operator from collections import Counter</pre> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: The <code>counter </code>and <code>collections </code>libraries are built-in to Python and do not require installation.</p> <hr class="wp-block-separator" /> <h2>Method 1: Use NumPy and count()</h2> <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> <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)) dup_num = the_list[random.randint(0, 19)] dup_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!') except ValueError: print(f'Incorrect value. Bye')</pre> <p>The previous code snippet performs the following steps:</p> <ul> <li>Our first line generates and saves 20 random numbers to <code>the_list</code>. </li> <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> <li>Finally, we determine how many occurrences of <code>dup_num</code> were found using <code>count()</code>. </li> <li>The result saves to <code>dup_count</code>.</li> </ul> <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> <p>The user is prompted to enter the total number of occurrences. To confirm, the user presses the <code><Enter></code> key. The value entered is then compared to <code>dup_count</code>, and a message indicates the outcome.</p> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <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> <hr class="wp-block-separator" /> <h2>Method 2: Use operator countOf()</h2> <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> <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)] dup_num = the_list[random.randint(0, 19)] dup_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!') except ValueError: print(f'Incorrect value. Bye')</pre> <p>This code snippet performs the following steps:</p> <ul> <li>Our first line generates and saves 20 random numbers to <code>the_list</code>. </li> <li>Next, <code>dup_num</code> is created by generating and saving one (1) random number from <code>the_list</code>. </li> <li>Finally, we determine how many occurrences of <code>dup_num</code> were found using <code><code>operator.countOf()</code></code>. </li> <li>The result saves to <code>dup_count</code>.</li> </ul> <p>Inside the <code>try</code> statement, <code>the_list </code>is output to the terminal. </p> <p>The user is prompted to enter the total number of occurrences. To confirm, the user presses the <code><Enter></code> key. </p> <p>The value entered is then compared to <code>dup_count</code>, and a message indicates the outcome.</p> <hr class="wp-block-separator" /> <h2>Method 3: Use a For Loop</h2> <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> <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)] dup_num = the_list[random.randint(0, 19)] dup_count = 0 for 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!') except ValueError: print(f'Incorrect value. Bye')</pre> <p>The previous code snippet performs the following steps:</p> <ul> <li>Our first line generates and saves 20 random numbers to <code>the_list</code>. </li> <li>Next, <code>dup_num</code> is created by generating and saving one (1) random number from <code>the_list</code>. </li> <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> <li>If found, <code>dup_count</code> is increased by one (1).</li> </ul> <p>Inside the <code>try</code> statement, <code>the_list </code>is output to the terminal. </p> <p>The user is prompted to enter the total number of occurrences. To confirm, the user presses the <code><Enter></code> key. </p> <p>The value entered is then compared to <code>dup_count</code>, and a message indicates the outcome.</p> <hr class="wp-block-separator" /> <h2>Method 4: Counter()</h2> <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> <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)] dup_num = the_list[random.randint(0, 19)] d = Counter(the_list) dup_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!') except ValueError: print(f'Incorrect value. Bye')</pre> <p>The previous code snippet performs the following steps:</p> <ul> <li>Our first line generates and saves 20 random numbers to <code>the_list</code>. </li> <li>Next, <code>dup_num</code> is created by generating and saving one (1) random number from <code>the_list</code>. </li> <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> <li>If found, <code>dup_count</code> is increased by one (1).</li> </ul> <p>Inside the <code>try</code> statement, <code>the_list </code>is output to the terminal. </p> <p>The user is prompted to enter the total number of occurrences. To confirm, the user presses the <code><Enter></code> key. </p> <p>The value entered is then compared to <code>dup_count</code>, and a message indicates the outcome.</p> <hr class="wp-block-separator" /> <h2>Summary</h2> <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> <p>Good Luck & Happy Coding!</p> <hr class="wp-block-separator" /> </div> https://www.sickgaming.net/blog/2022/04/10/how-to-count-the-occurrences-of-a-list-element/ |