Python – Remove Tuples with difference greater than K

PythonServer Side ProgrammingProgramming

<p>When it is required to remove tuples with difference greater than K, use the abs() method.</p><p>Below is a demonstration of the same &minus;</p><h2>Example</h2><pre class="demo-code notranslate language-python" data-lang="python">my_tuple = [(41, 18), (21,57), (39, 22), (23, 42), (22, 10)] print(&quot;The tuple is :&quot;) print(my_tuple) K = 20 my_result = [element for element in my_tuple if abs(element[0] - element[1]) &lt;= K] print(&quot;The result is :&quot;) print(my_result)</pre><h2>Output</h2><pre class="result notranslate">The tuple is : [(41, 18), (21, 57), (39, 22), (23, 42), (22, 10)] The result is : [(39, 22), (23, 42), (22, 10)]</pre><h2>Explanation</h2><ul class="list"><li><p>A tuple is defined and displayed on the console.</p></li><li><p>The value for K is defined.</p></li><li><p>A list comprehension is used to iterate over the list, and the difference of each element of the tuple is compared with K.</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>
raja
Updated on 08-Sep-2021 06:45:23

Advertisements