
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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.
Below is a demonstration of the same −
Example
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)
Output
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,)]
Explanation
A list of the tuple is defined and is displayed on the console.
A value for ‘K’ is initialized.
List comprehension is used to iterate over the list of the tuple.
It is checked to see all the tuples in the list have the same size.
It is converted to a list, and is assigned to a variable.
It is displayed as output on the console.
Advertisements