![]() |
VOOZH | about |
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.
List comprehension provides a concise way to filter tuples based on their length.
[(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.
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.
[(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.
This method iterates through each tuple and adds it to a new list only if its length is not equal to K.
[(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.
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().
[(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.