Example:
tuple = ("python", "includehelp", 43, 54.23)
Removing all Tuples of Length K
In the program, we are given a list containing tuples of variable length. And we will be printing a list that will contain all tuples from the list except the ones with length k.
Example:
Input:
[(1, 4), (2), (4,5,6,8), (26), (3, 0, 1), (4)] k = 1
Output:
[(1, 4), (4, 5, 6, 8), (3, 0, 1)]
To eliminate all tuples of length k we need to traverse the list of tuples and then find the lengths of all the tuples and remove tuples from the list whose length is equal to k.
In Python programming language, there are multiple ways to perform a single task in different ways and it depends on the programmer and then the need of the software being developed that which one should be used.
Method 1:
One method to remove the tuples is using the filter method which filters off every element which does not satisfy the entry condition.
In the filter method, we will pass the lambda function to iterate over all elements of the array and check if the length is equal to k or not. Elements with length K are not allowed to pass through the function. The list returned by the filter method is the required list.
Program:
Output:
The same task can be performed using list comprehension that does iteration over the list and checking of elements with length other than k. And returns their values.
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer