Program to remove the K length tuple using Python

Introduction

The task is to find and remove the K length tuple.

Program to remove the K length tuple using Python 

 

Program

Approach 1

ip_list = [ (2, ), (1, 6), (1, ), (3, 7)]
print("The given list  : "+str(ip_list))
K = 1

#Using filter()+lambda
output = list(filter(lambda x : len(x) != K, ip_list))
print("Output list: "+str(output))

Output:

Program to remove the K length tuple using Python Output 1

Approach 2

ip_list = [ (2, ), (1, 6), (1, ), (3, 7)]
print("The given list : "+str(ip_list))
K = 1

#Using lis comprehension and len()
output = [i for i in ip_list if len(i) != K]
print("Output list: "+str(output))

Output:

Program to remove the K length tuple using Python Output 2

Explanation

In our first approach, we have used filter function with lambda. The lambda function extracts the K length elements from the tuple and filter() function is used to filter the output.

The second approach is list comprehension. The elements having length not equal to K is extracted and stored to the output variable.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.