Given list of tuples, remove all the tuples with length K.
Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K = 2
Output : [(4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
Explanation : (4, 5) of len = 2 is removed.
Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K = 3
Output : [(4, 5), (4, ), (1, ), (3, 4, 6, 7)]
Explanation : 3 length tuple is removed.
This is one of the ways in which this task can be performed. In this, we iterate for all elements in loop and perform the required task of removal of K length elements using conditions.
OutputThe original list : [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
Filtered list : [(4, 5), (8, 6, 7), (3, 4, 6, 7)]
Yet another way to solve this problem. In this, we perform filtering using filter() and lambda function to extract just non K length elements using len().
OutputThe original list : [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
Filtered list : [(4, 5), (8, 6, 7), (3, 4, 6, 7)]
OutputThe original list : [(4, 5), (4,), (8, 6, 7), (1,), (3, 4, 6, 7)]
Filtered list : [(4, 5), (8, 6, 7), (3, 4, 6, 7)]
The given problem is to remove tuples of a given length k from a list of tuples and return the filtered list.
1.Read the original list and the value of k.
2.Create an empty list to store the filtered tuples.
3.Use the map() function with a lambda function as its first argument to iterate over each tuple in the original list.
4.Use the filter() function with a lambda function as its first argument to filter out the tuples whose length is equal to k.
5.Convert the resulting map object into a list using the list() function and store it in the filtered_list.
6.Print the filtered_list.
Output[(4, 5), (8, 6, 7), (3, 4, 6, 7)]
OutputThe original list : [(4, 5), (4,), (8, 6, 7), (1,), (3, 4, 6, 7)]
Filtered list : [(4, 5), (8, 6, 7), (3, 4, 6, 7)]