Open In App

Python – Extract tuples having K digit elements

Last Updated : 30 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of tuples, extract all tuples having K digit elements.

Input : test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (78, )], K = 2 
Output : [(34, 55), (12, 45), (78,)] 
Explanation : All tuples have numbers with 2 digits.

Input : test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (782, )], K = 3 
Output : [(782,)] 
Explanation : All tuples have numbers with 3 digits. 

Method #1 : Using all() + list comprehension

In this, we check for each element being of K digit by converting to string and checking its length. The all() is used to check if all elements are of similar size.

Python3




# Python3 code to demonstrate working of
# Extract K digit Elements Tuples
# Using all() + list comprehension
 
# initializing list
test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (78, )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# using len() and str() to check length and
# perform string conversion
res = [sub for sub in test_list if all(len(str(ele)) == K for ele in sub)]
 
# printing result
print("The Extracted tuples : " + str(res))


Output:

The original list is : [(54, 2), (34, 55), (222, 23), (12, 45), (78,)] The Extracted tuples : [(34, 55), (12, 45), (78,)]

Time Complexity: O(n) where n is the number of elements in the list “test_list”.  list comprehension + all() performs n number of operations.
Auxiliary Space: O(n), extra space of size n is required

Method #2 : Using all() + filter() + lambda

This is similar to above method, difference being filter() and lambda is used to solve problem of filtering.

Python3




# Python3 code to demonstrate working of
# Extract K digit Elements Tuples
# Using all() + filter() + lambda
 
# initializing list
test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (78, )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# filter() and lambda used for task of filtering
res = list(filter(lambda sub: all(len(str(ele)) == K for ele in sub), test_list))
 
# printing result
print("The Extracted tuples : " + str(res))


Output:

The original list is : [(54, 2), (34, 55), (222, 23), (12, 45), (78,)] The Extracted tuples : [(34, 55), (12, 45), (78,)]

Method #3: Using list(),map(),str() and len() methods

Converting each tuple element to string and converting that tuple to list after that iterating over the list finding the length of each element and appending to a new list.If the new list is [K,K] or[K] then the tuples have K digit elements.

Python3




# Python3 code to demonstrate working of
# Extract K digit Elements Tuples
 
# initializing list
test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (78, )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialising K
K = 2
 
res=[]
for i in test_list:
    x=list(map(str,i))
    p=[]
    for j in x:
        p.append(len(j))
    if(p==[K,K] or p==[K]):
        res.append(i)
     
# printing result
print("The Extracted tuples : " + str(res))


Output

The original list is : [(54, 2), (34, 55), (222, 23), (12, 45), (78,)]
The Extracted tuples : [(34, 55), (12, 45), (78,)]

Method#4:Using a for loop and string slicing

Algorithm:

  1. Initialize the list of tuples.
  2. Print the original list.
  3. Initialize the value of K to 2.
  4. Initialize an empty list called res to store the extracted tuples.
  5. For each tuple in the list, set the flag to True.
  6. For each element in the tuple, check if the length of the string representation of the element is equal to K. If it’s not, set the flag to False and break out of the loop.
  7. If the flag is still True after checking all elements of the tuple, append the tuple to the res list.
  8. Print the extracted tuples.

Python3




# Python3 code to demonstrate working of
# Extract K digit Elements Tuples
# Using for loop and string slicing
 
# initializing list
test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (78, )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# using a for loop and string slicing to check length
res = []
for tup in test_list:
    flag = True
    for ele in tup:
        if len(str(ele)) != K:
            flag = False
            break
    if flag:
        res.append(tup)
 
# printing result
print("The Extracted tuples : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original list is : [(54, 2), (34, 55), (222, 23), (12, 45), (78,)]
The Extracted tuples : [(34, 55), (12, 45), (78,)]

Time complexity:
The time complexity of this code is O(n*m), where n is the length of the list of tuples and m is the average length of the tuples. The for loop iterates over each tuple in the list, and then iterates over each element in the tuple to check its length. Since the length of the tuples can vary, we use m to represent the average length of the tuples.

Space complexity:
The space complexity of this code is O(k), where k is the length of the res list. The res list stores the extracted tuples, which can be at most the same length as the original list of tuples.

Method #6: Using a generator expression and tuple unpacking

We can use a generator expression to iterate through the tuples and yield only the tuples that contain K digits elements. We can use tuple unpacking to check the length of each element in the tuple.

Python3




# Python3 code to demonstrate working of
# Extract K digit Elements Tuples
 
# initializing list
test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (78, )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialising K
K = 2
 
# Using a generator expression and tuple unpacking
res = tuple(t for t in test_list if all(len(str(e)) == K for e in t))
 
# printing result
print("The Extracted tuples : " + str(res))


Output

The original list is : [(54, 2), (34, 55), (222, 23), (12, 45), (78,)]
The Extracted tuples : ((34, 55), (12, 45), (78,))

Time complexity: O(nk), where n is the length of the list and k is the length of the largest element in the list.
Auxiliary space: O(1), because we are not using any extra data structures to store intermediate results.



Similar Reads

Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read
Python program to find Tuples with positive elements in List of tuples
Given a list of tuples. The task is to get all the tuples that have all positive elements. Examples: Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [(4, 5, 9)] Explanation : Extracted tuples with all positive elements. Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [] Explanation : No tuple wit
10 min read
Python program to find tuples which have all elements divisible by K from a list of tuples
Given a list of tuples. The task is to extract all tuples which have all elements divisible by K. Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6 Output : [(6, 24, 12), (60, 12, 6)] Explanation : Both tuples have all elements multiple of 6. Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5 Output : [(60, 10, 5)
7 min read
Python - Extract tuples with elements in Range
Given list of tuples, extract tuples having elements in range. Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 5, 6 Output : [(5, 6)] Explanation : Only 1 tuple lies in range of 5-6. Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 1, 10 Output : [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)] Explanat
4 min read
Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to count unique #
5 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways in which this can be performed. Method #1: Using
7 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this task can be performed. Method 1 (Using eval() + list
4 min read
three90RightbarBannerImg