

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract tuples having K digit elements in Python
<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 −</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/y9BrHaYE" rel="nofollow" target="_blank"> Live Demo</a></p><pre class="prettyprint notranslate">my_list = [(34, 56), (45, 6), (111, 90), (11, 35), (78, )] print("The list is : ") print(my_list) K = 2 print("The value of K has been initialized to" + "str(K)") my_result = [sub for sub in my_list if all(len(str(elem)) == K for elem in sub)] print("The tuples extracted are : ") 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 ‘K’ 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>
- Related Questions & Answers
- Python – Reform K digit elements
- Python program to extract Mono-digit elements
- Python – Extract tuples with elements in Range
- Find top K frequent elements from a list of tuples in Python
- Python – Trim tuples by K
- Remove Tuples of Length K in Python
- Remove tuples having duplicate first value from given list of tuples in Python
- Python program to find tuples which have all elements divisible by K from a list of tuples
- Python - Get sum of tuples having same first value
- Find Dissimilar Elements in Tuples in Python
- Python – Filter consecutive elements Tuples
- Trim tuples by N elements in Python
- Python – Filter Tuples Product greater than K
- Count n digit numbers not having a particular digit in C++
- Python program to find Tuples with positive elements in List of tuples
Advertisements