Given list of tuples, remove all the tuples with length K. For Example:
Input : [(4, 5), (4, ), (8, 6, 7), (1, ), (2, 3), (3, 4, 6, 7)], K = 2
Output : [(4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
Explanation: tuple (4, 5) and (2, 3) has length 2, so they are removed.
Let's explore different methods to remove tuples of length K in python.
Using list comprehension
List comprehension provides a concise way to filter tuples based on their length.
t1 = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
K = 1
res = [ele for ele in t1 if len(ele) != K]
print(str(res))
Output
[(4, 5), (8, 6, 7), (3, 4, 6, 7)]
Explanation: [ele for ele in t1 if len(ele) != K] creates a new list containing only the tuples whose length is not equal to K.
Using filter() + lambda + len()
This method removes tuples of a specific length using a lambda condition inside filter(). The len() function checks each tuple’s size, and lambda defines the condition to keep only those whose length isn’t equal to K.
t1 = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
K = 1
res = list(filter(lambda x : len(x) != K, t1))
print(str(res))
Output
[(4, 5), (8, 6, 7), (3, 4, 6, 7)]
Explanation: filter(lambda x: len(x) != K, t1): applies a filter function that keeps only the tuples whose length is not equal to K.
Using a loop
This method iterates through each tuple and adds it to a new list only if its length is not equal to K.
t1 = [(4, 5), (4,), (8, 6, 7), (1,), (3, 4, 6, 7)]
K = 1
res = []
for t in t1:
if len(t) != K:
res.append(t)
print(res)
Output
[(4, 5), (8, 6, 7), (3, 4, 6, 7)]
Explanation: Iterates through each tuple and appends it to res only if its length is not equal to K.
Using map() and lambda function
This approach combines filter() to exclude tuples of a given length and map() to return the remaining ones. The lambda function defines the condition based on tuple length using len().
t1 = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
k = 1
n1 = list(map(lambda x: x, filter(lambda x: len(x) != k, t1)))
print(n1)
Output
[(4, 5), (8, 6, 7), (3, 4, 6, 7)]
Explanation: list(map(lambda x: x, filter(lambda x: len(x) != k, t1))): filters t1 to keep only tuples whose length is not k and returns them as a list.