
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- Python – Extract tuples with elements in Range
- Python – Reform K digit elements
- Python program to extract Mono-digit elements
- Find top K frequent elements from a list of tuples in Python
- Python – Trim tuples by K
- Python program to find tuples which have all elements divisible by K from a list of tuples
- Remove Tuples of Length K in Python
- Remove tuples having duplicate first value from given list of tuples in Python
- Python – Filter consecutive elements Tuples
- Find Dissimilar Elements in Tuples in Python
- Python – Filter Tuples Product greater than K
- Trim tuples by N elements in Python
- Python Program to Extract Strings with a digit
- Python program to find Tuples with positive elements in List of tuples
- Python - Get sum of tuples having same first value

Advertisements