Extract tuples having K digit elements in Python

PythonServer Side ProgrammingProgramming

<p>When it is required to extract tuples that have a specific number of elements, list comprehension can be used. It iterates over the elements of the list of tuple and puts forth condition that needs to be fulfilled. This will filter out the specific elements and stores them in another variable.</p><p>Below is a demonstration of the same &minus;</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/y9BrHaYE" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">my_list = [(34, 56), (45, 6), (111, 90), (11, 35), (78, )] print(&quot;The list is : &quot;) print(my_list) K = 2 print(&quot;The value of K has been initialized to&quot; + &quot;str(K)&quot;) my_result = [sub for sub in my_list if all(len(str(elem)) == K for elem in sub)] print(&quot;The tuples extracted are : &quot;) print(my_result)</pre><h2>Output</h2><pre class="result notranslate">The list is : [(34, 56), (45, 6), (111, 90), (11, 35), (78,)] The value of K has been initialized tostr(K) The tuples extracted are : [(34, 56), (11, 35), (78,)]</pre><h2>Explanation</h2><ul class="list"><li><p>A list of the tuple is defined and is displayed on the console.</p></li><li><p>A value for &lsquo;K&rsquo; is initialized.</p></li><li><p>List comprehension is used to iterate over the list of the tuple.</p></li><li><p>It is checked to see all the tuples in the list have the same size.</p></li><li><p>It is converted to a list, and is assigned to a variable.</p></li><li><p>It is displayed as output on the console.</p></li></ul>
Updated on 14-Apr-2021 12:37:33