Python – Average digits count in a List

PythonServer Side ProgrammingProgramming

<p>When it is required to count average digits in a list, a simple iteration, the &lsquo;str&rsquo; method and the &lsquo;/&rsquo; operator is used.</p><p>Below is a demonstration of the same &minus;</p><h2>Example</h2><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">my_list = [324, 5345, 243, 746, 432, 463, 946787] print(&quot;The list is :&quot;) print(my_list) sum_digits = 0 for ele in my_list: &nbsp; &nbsp;sum_digits += len(str(ele)) &nbsp; &nbsp; my_result = sum_digits / len(my_list) print(&quot;The result is :&quot;) print(my_result)</pre><h2>Output</h2><pre class="result notranslate">The list is : [324, 5345, 243, 746, 432, 463, 946787] The result is : 3.5714285714285716</pre><h2>Explanation</h2><ul class="list"><li><p>A list is defined and displayed on the console.</p></li><li><p>A variable is initialized to 0.</p></li><li><p>The list is iterated over, and the sum of the digits is calculated by first converting the element to a list and determining its length using &lsquo;len&rsquo; method.</p></li><li><p>The average of these digits is calculated.</p></li><li><p>This result is assigned to a variable.</p></li><li><p>This is the output that is displayed on the console.</p></li></ul>
Updated on 06-Sep-2021 08:33:22